Home > Net >  How to replace forEach with map for the below in Javascript
How to replace forEach with map for the below in Javascript

Time:11-19

There are two arrays and both have id attributes along with other properties. Requirement is compare two arrays and create new to add age property to corresponding object in arr1

let arr1 = [{
  id: 1,
  name: 'a'
}, {
  id: 2,
  name: 'b'
}, {
  id: 3,
  name: 'c'
}];

let arr2 = [{
  id: 1,
  age: 20
}, {
  id: 3,
  age: 35
}];
const newArr = [];

arr1.forEach(obj => {
  return arr2.forEach((obj2) => {
    if (obj.id === obj2.id) {
      newArr.push(Object.assign({}, obj, {
        age: obj2.age
      }))
    }
  })
})
 console.log(newArr);
//outputs [{id:1, name: 'a', age:20}, {id:3, name: 'c', age:35}]
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I don't know if it's the most elegant solution but you can create your function and map with it:

let arr1 = [{
    id: 1,
    name: 'a'
  }, {
    id: 2,
    name: 'b'
  }, {
    id: 3,
    name: 'c'
}];
  
let arr2 = [{
    id: 1,
    age: 20
  }, {
    id: 3,
    age: 35
}];

function addAge(elt, arr2) {
    let elt_w_age = arr2.find(x => x.id === elt.id);
    if (elt_w_age != null) {
        elt.age = elt_w_age.age
        return elt
    }
    else {
        return null
    }
}

console.log(arr1.map(x => addAge(x, arr2)).filter(x => x !== null))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related