我还不是 javascript 专家,但我想在具有不同值的对象数组中添加一个新属性,该数组采用数组格式。
const mainArray = [{name: 'John', age: 30}, {name: 'Jane', age: 25}]
const country = ['Germany', 'Japan']
const res = mainArray.map(x => {
return {
name: x.name,
age: x.age,
country: country
}
})
我尝试了这个,但它不起作用
预计是这样的
result = [{name: 'John', age: 30, country: 'Germany'}, {name: 'Jane', age: 25, country: 'Japan'}]
最佳答案
从您的示例代码中,您实际上使用整个数组设置了国家/地区的值。你应该使用索引
const mainArray = [{name: 'John', age: 30}, {name: 'Jane', age: 25}];
const country = ['Germany', 'Japan']
function addKey(arr, key, value) => {
const res = arr.map((x, index) => {
return {
...x,
[key]: value[index]
};
});
return res;
};
console.log(addKey(mainArray, 'country', country))
从这里,您可以在第二个参数中添加任何其他特定属性
希望这对你有帮助
关于javascript - 从对象数组中添加新的键和值集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75007902/