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

104
Vistas
How to compare/match id's in two seperate arrays, and retrieve some data into one object in javascript?

I have the following values -

const r = [{ id: 2, car: 'toyota}, {id: 1, car:'honda'}]

const s = [{ id: 2, name: 'Samuel'},{id: 1, name: 'James'}]

I want to match the arrays based on id and add name to each corresponding matched object id.

const res = [{id: , car: , name: }]

I have certain values I need to map together to make into one response object, so it needs to be an array of objects with various properties. I want to map based on an id and then loop through each object in the array and add the corresponding object. Kindly help, much appreciated!

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

0

You can easily achieve the result using Map and map

const r = [
  { id: 2, car: "toyota" },
  { id: 1, car: "honda" },
];

const s = [
  { id: 2, name: "Samuel" },
  { id: 1, name: "James" },
];

const map = new Map(r.map((o) => [o.id, o]));
const result = s.map((o) => ({ ...o, ...(map.get(o.id) ?? []) }));
console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

In this problem we need to filter the data & also need to map the data so for this direct filter operator won't work so I just solved your problem with a forEach loop.

const arr1 = [{ id: 2, car: 'toyota'}, {id: 1, car:'honda'}]

const arr2 = [{ id: 3, name: 'Samuel'},{id: 1, name: 'James'}]

const result = [];
arr1.forEach(arr1Obj=>{
  const matchedObject = arr2.find(arr2Obj=>arr2Obj.id==arr1Obj.id);
  if(matchedObject){
  result.push({...arr1Obj,...matchedObject});
  }
  
})
console.log(result);

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