我正在努力实现这样的目标:
let obj = [
{"id": "1"},
{"id": "2"},
{"id": "3"}
]
const arr = ["a", "b", "c"];
obj = addAtoO(arr, obj); // expected outcome: obj = [{"id": "1", "text": "a"}, {"id": "2", "text": "b"}, {}]
换句话说:动态地将数组中的值作为新值添加到对象。
这是我正在尝试的:
const addAtoO = (a, o) => {
o.map((i) => {
console.log(Object.keys(i));
// a.forEach((e) => {
// console.log(e);
// });
i['text'] = 'something'; // just add text for testing
});
return o;
};
obj = addAtoO(arr, obj);
console.log('result:');
console.log(obj);
但似乎必须有更好的方法。
Thank you so much guys. All your solutions are correct. I had to mark one so I picked the one that is the closest to this specific question.
最佳答案
您可以像使用 一样使用 map
,并使用它的索引从 arr
数组中获取值,并使用 obj< 中的值创建一个新对象
& arr
let obj = [{
"id": "1"
},
{
"id": "2"
},
{
"id": "3"
}
]
const arr = ["a", "b", "c"];
let output = obj.map(function(item, index) {
return Object.assign({}, item, {
text: arr[index]
})
})
console.log(output)
否则你也可以使用 forEach
并改变原始的 obj
数组
let obj = [{
"id": "1"
},
{
"id": "2"
},
{
"id": "3"
}
]
const arr = ["a", "b", "c"];
obj.forEach(function(item, index) {
item.text = arr[index]
})
console.log(obj)
关于javascript - 将项目从数组动态添加到对象作为新值的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53524835/