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
Find items by id's from another array and add to them new property

I want to find all objects in items array which is on groupedItems array by 'id' and add to each item isGrouped: true property.

const items = [
          { id: 1, name: "item1" },
          { id: 2, name: "item2" },
          { id: 3, name: "item3" }
        ];
        
const groupedItems = [
          { id: 2, name: "item2" },
          { id: 3, name: "item3" }
        ];

so the result should be:

items = [
              { id: 1, name: "item1" },
              { id: 2, name: "item2", isGrouped:true },
              { id: 3, name: "item3", isGrouped: true }
            ];

any ideas ?

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

0

You can iterate over the items array using map, creating an isGrouped property which is the result of calling findIndex on the item.id property in the groupedItems id values:

const items = [
          { id: 1, name: "item1" },
          { id: 2, name: "item2" },
          { id: 3, name: "item3" }
        ];
        
const groupedItems = [
          { id: 2, name: "item2" },
          { id: 3, name: "item3" }
        ];
        
const result = items.map(item => ({
   ...item, 
   isGrouped : groupedItems.findIndex(g => g.id == item.id) >= 0 
   }
));

console.log(result);

Note that I've added isGrouped as false for those objects which are not grouped, rather than omitting the property. It seems that it should be easier to just test a boolean value of a property rather than checking whether the property exists. If you really want to omit the property, you could do something like this:

const items = [
          { id: 1, name: "item1" },
          { id: 2, name: "item2" },
          { id: 3, name: "item3" }
        ];
        
const groupedItems = [
          { id: 2, name: "item2" },
          { id: 3, name: "item3" }
        ];
        
const result = items.map(item => 
  groupedItems.find(g => g.id == item.id) ? { ...item, isGrouped : true } : item
);

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