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

164
Views
How can I find objects with same keys values in array?

I have an array of objects that looks like this:

  const arr = [
    { type: 'type', fields: ['field1'] },
    { type: 'type2' },
    { type: 'type', fields: ['field2'] },
  ]

And I need to find objects with the same type to merge fields key in them, like this:

  const arr = [
    { type: 'type', fields: ['field1', 'field2'] },
    { type: 'type2' },
    { type: 'type', fields: ['field1', 'field2'] },
  ]

My plan was to filter through the array, but my problem is that I don't know which type will send me API, so filtering by item.type wouldn't work for me.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If that is the exact solution that you want. Following code snippet may help you.

    const arr = [
      { type: 'type', fields: ['field1']},
      { type: 'type2'},
      { type: 'type', fields: ['field2']}
    ]
    
    const modifyArr = (data) => {
      let res = [];
      arr.map((item) => {
          if(item.type == data.type){
            if(Object.keys(item).includes('fields')){
              res = res.concat(item.fields);
            }
          }
      });
      return Object.keys(data).includes('fields') ? { type: data.type, fields: res } : { type: data.type };

}

let newArr = arr.map(item => modifyArr(item));

console.log(newArr); 

This will print

[
    { type: 'type', fields: ['field1', 'field2'] },
    { type: 'type2' },
    { type: 'type', fields: ['field1', 'field2'] },
  ]
about 4 years ago · Juan Pablo Isaza Report

0

const arr = [{ type: 'type', fields: ['field1']}, { type: 'type2'}, { type: 'type', fields: ['field2']}];

result = arr.map(({ type }) => {
    const fields = arr.filter((o) => o.type === type).flatMap((e) => e.fields);
    return { type, ...fields[0] ? { fields } : {} };
});

console.log(result);
//[
//    {"type": "type", "fields": ["field1", "field2"]},
//    {"type": "type2"},
//    {"type": "type", "fields": ["field1", "field2"]}
//]

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!