Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

99
Vistas
How to replace forEach with map for the below in Javascript

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda