Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to iterate over object and dynamically assign values to keys

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"
//   },
// ]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading