【发布时间】:2020-02-06 15:28:49
【问题描述】:
我有一个对象数组,我希望它成为一个可以去{ 44: "autoTest", 94: "autoTest", ...}的对象
[
0: {
id: 1,
name: "test",
description: "a description"
},
1: {
id: 2,
name: "test 2",
description: "a description french baguette"
}
]
会变成
{
1: "test",
2: "test2"
}
到目前为止,我的代码带有一些 console.log() :
const { options } = this.state;
console.log(options); // […] 0: Object { id: 44, name: "autoTest", description: "test uniUpdate", … } 1: Object { id: 94, name: "autoTest", description: "test uni", … }
let obj2 = {};
if (options.length > 0) {
options.map((item, key) => {
const id = item.id;
const name = item.name;
let obj1 = { [id]: name };
console.log(obj1); // Object { 44: "autoTest" } for example
obj2 = { ...obj1 };
});
console.log(obj2); // Object { 16: "Test 3" } is called like two times and is obviously not what I expected
}
一些提示?
【问题讨论】:
-
我想你想使用
forEach甚至reduce -
obj2 = {...obj2, ...obj1} -
obj2 = Object.assign(obj2, obj1) -
为什么要这个对象而不是数组?
-
@YannickK 可能是因为 ID 不一定是连续的。
标签: javascript reactjs spread