Home > Software engineering >  Adding new sets of key and value from array of object
Adding new sets of key and value from array of object

Time:01-05

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.

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'}]

CodePudding user response:

from your sample code, you actually setting the value of country with the whole array. 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

hope this help you

CodePudding user response:

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)

CodePudding user response:

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,

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

  • Related