从对象数组中添加新的键和值集



im还不是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'}]

从您的示例代码中,您实际上用整个数组设置了country的值。你应该使用索引

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

从这里开始,您可以在第二个arg 中添加任何其他特定属性

希望这能帮助你

You need to use index variable to access the values from other array

const mainArray = [{name: 'John', age: 30}, {name: 'Jane', age: 25}];
const country = ['Germany', 'Japan']
const res = mainArray.map((x,i) => {
return {
name: x.name,
age: x.age,
country: country[i] // <-- i added [i]
}
})
console.log(res)

如果country元素的索引与mainArray的索引相关,则可以使用index参数的.map过载

修改:以说明country数组中没有包含足够的元素来匹配您的mainArray:

const mainArray = [{name: 'John', age: 30}, {name: 'Jane', age: 25}]
const country = ['Germany', 'Japan']
//use the overload of .map with the index, so you can set the new
//property to the value of the country array via the index parameter
const res = mainArray.map((x, index) => {
return {
name: x.name,
age: x.age,
country: country[index] || 'unknown'
}
});
console.log(res);

最新更新