Home > front end >  How to modify an array of objects to new values based on another array in ReactJs?
How to modify an array of objects to new values based on another array in ReactJs?

Time:07-11

I have 2 arrays as below, I want to update the array1 value based on array2 value for example in array1.name I want to set it's value to array2.uName's value and updated array should be const array1 = [{name: "aman", age:"26"},...]. How to achieve this in React?

Actually I want to map through new modified array and return an component with the data combined both arrays but array1 should be updated based on array2 which I am getting from api.

const array1 = [{
    name: "abc",
    age: "123"
  },
  {
    name: "bcd",
    age: "456"
  },
];

const array2 = [{
    uAddress: "India",
    uAge: "26",
    uNum: "12345",
    uName: "aman"
  },
  {
    uAge: "46",
    uAddress: "India",
    uNum: "6789",
    uName: "rohan"
  },
];

CodePudding user response:

Use forEach to iterate through your list, and set the fields accordingly.

array1.forEach((person, index) => { 
  person.name = array2[index].uName; 
  person.age = array2[index].uAge;
})

Result: [ { name: 'aman', age: '26' }, { name: 'rohan', age: '46' } ]

update:

array1.forEach((person, index) => {
  let copyFromPerson = array2.find(ele => ele.id === person.id)
  person.name = copyFromPerson.uName; 
  person.age = copyFromPerson.uAge;
})

CodePudding user response:

This isn't really a React-specific thing, but if you use a forEach higher-order function you can achieve this update.

array1.forEach((item, index) => { 
   item.age = array2[index].uAge
   item.name = array2[index].uName
  })

console.log(array1[0]) // {name: "aman", age: "26"}

Note: In the description, you said array1.name. I just want to make sure you know that that won't work. array1 is an array of objects, so in order to use dot notation to access a property, you need to clarify which index of the array you want access. Such as array1[0] or array1[1]. Then you can do array1[0].name

  • Related