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

173
Vistas
Merge two array of objects with nested id

I have two arrays of objects that I need to combine where the nested ID (connect.id) of the second array matches the id of the first but can't see how to do it

can anyone help?

const arr1 = [
  { "id": 7619209572755, "title": "Title 1" },
  { "id": 7619209157372, "title": "Title 2" },
  { "id": 7619209921625, "title": "Title 3" }
];  
const arr2 = [
  {
    "id": 7619217289192,
    "connect": [
      { "id": 7619209157372, "title": "Title 1" }
    ],
    "value": "1"
  },
  {
    "id": 7619217242206,
    "connect": [
      { "id": 7619209921625, "title": "Title 2" }
    ],
    "value": "2"
  }
];
const expectedResult = [
  { "id": 7619209572755, "title": "Title 1" },
  { "id": 7619209157372, "title": "Title 2", "value": "1" },
  { "id": 7619209921625, "title": "Title 3", "value": "2" }
]
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

  1. Using Array#reduce, iterate over arr2 to map every connect element's id with the its object's value in a Map
  2. Using Array#map, iterate over arr1, if an element's id is in the map, set its value

const 
  arr1 = [ { "id": 7619209572755, "title": "Title 1" }, { "id": 7619209157372, "title": "Title 2" }, { "id": 7619209921625, "title": "Title 3" } ],
  arr2 = [
    {
      "id": 7619217289192,
      "connect": [ { "id": 7619209157372, "title": "Title 1" } ],
      "value": "1",
    },
    {
      "id": 7619217242206,
      "connect": [ { "id": 7619209921625, "title": "Title 2" } ],
      "value": "2",
    }
  ];
  
const connectValueMap = arr2.reduce((map, { connect = [], value}) => {
  connect.forEach(({ id }) => map.set(id, value));
  return map;
}, new Map);

const merged = arr1.map(e => {
  const value = connectValueMap.get(e.id);
  if(value) e.value = value;
  return e;
});

console.log(merged);

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