简体   繁体   English

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

[英]Adding new sets of key and value from array of object

im not yet expert in javascript but I wanted to add a new property in an array of objects with different values which is in an array format.我还不是 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
    }
})

i tried this but its not working我试过了,但没用

expected to be like this预计会是这样

result = [{name: 'John', age: 30, country: 'Germany'}, {name: 'Jane', age: 25, country: 'Japan'}]

from your sample code, you actually setting the value of country with the whole array.从您的示例代码中,您实际上使用整个数组设置了 country 的值。 you should use index你应该使用索引

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

from here, you can add any other specific property in the second arg从这里,您可以在第二个 arg 中添加任何其他特定属性

hope this help you希望这对你有帮助

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)

If the index of the country element is meant to be related to the index of mainArray , you can use the overload of .map with the index parameter,如果country元素的索引与mainArray的索引相关,则可以使用带有index参数的.map的重载,

modified: to account for country array not containing enough elements to match with your mainArray :修改:考虑到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);

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

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