PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 25, 2022

[FIXED] how to iterate over object and dynamically assign values to keys

 July 25, 2022     arrays, javascript, json, object     No comments   

Issue

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


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);



Answered By - jeremy-denis
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing