Home > Blockchain >  how to iterate over object and dynamically assign values to keys
how to iterate over object and dynamically assign values to keys

Time:07-06

Hella all,

so I am struggling with the following problem: I have an object with some keys and values. I would like to take them out and make a new array of objects. Here is the code, as it describes my problem better.

const sourceObj = {
  test1: "a",
  test2: "b",
  test3: "c",
  test4: "d",
  test5: "e"
};

const myTable = [];

for (let value of sourceObj) {
  for (let i = 1; i < 6; i  ) {
    const targetObject = {
      foo: "foo",
      year: value.test   i,
      bar: "bar"
    };
    myTable.push(targetObject);
  }
}

console.log(myTable);

// expected output
// [
//   {
//     foo: "foo",
//     year: "a",
//     bar: "bar"
//   },
//   {
//     foo: "foo",
//     year: "b",
//     bar: "bar"
//   },
//   ...
//   {
//     foo: "foo",
//     year: "e",
//     bar: "bar"
//   },
// ]

CodePudding user response:

you can iterate on object keys and use method array.map to get the expected object

const sourceObj = {
  test1: "a",
  test2: "b",
  test3: "c",
  test4: "d",
  test5: "e"
};

const myTable = Object.keys(sourceObj).map((key) => {
  return {
      foo: "foo",
      year: sourceObj[key],
      bar: "bar"
    };
});

console.log(myTable);

CodePudding user response:

You can simply use Object.values and map over it

const sourceObj = {
  test1: "a",
  test2: "b",
  test3: "c",
  test4: "d",
  test5: "e"
};

const myTable = Object.values(sourceObj).map(year => ({
  foo: "foo",
  year,
  bar: "bar"
}))
console.log(myTable);

CodePudding user response:

const sourceObj = {
  test1: "a",
  test2: "b",
  test3: "c",
  test4: "d",
  test5: "e"
};

const myTable = [];

for(item in sourceObj){
  myTable.push(
    {
      foo : "foo",
      year : sourceObj[item],
      bar : "bar"
    }
  );
}

console.log(myTable);

CodePudding user response:

Try this :

let myTable = Object.values(sourceObj).map((element) => ({
    foo: "foo",
    year: element,
    bar: "bar"
 }));

CodePudding user response:

You can use the for...in statement

The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.

const sourceObj = {
  test1: "a",
  test2: "b",
  test3: "c",
  test4: "d",
  test5: "e"
};

const myTable = [];

for (let key in sourceObj) {
    const targetObject = {
      foo: "foo",
      year: sourceObj[key],
      bar: "bar"
    };
    myTable.push(targetObject);
}

console.log(myTable);

  • Related