简体   繁体   English

如何迭代对象并将值动态分配给键

[英]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您可以迭代对象键并使用方法 array.map 来获取预期的对象

 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您可以简单地使用Object.values并映射它

 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您可以使用for...in语句

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. for...in语句迭代对象的所有可枚举属性,这些属性以字符串为键(忽略以符号为键的),包括继承的可枚举属性。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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