2

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

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.