简体   繁体   中英

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

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

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

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

Try this :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM