Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!