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

92
Views
Javascript merge objects with same property

I have an array of objects like this :

const arr = [
  {"id" : 1, "name" : "john", "age": 12, "fruits": "banana"},
  {"id" : 2, "name" : "john", "age": 12, "fruits": "apple"}
  {"id" : 3, "name" : "maria", "age": 13, "fruits": "grappes"}
  {"id" : 4, "name" : "maria", "age": 13, "fruits": "blackberry"}
  {"id" : 5, "name" : "camille", "age": 12, "fruits": "cherry"}
]

I would like to have a single object for each person (name) and add their objects.

So the final array would be :

const arr = [
  {"id" : 1, "name" : "john", "age": 12, "fruits": ["banana", "apple"]},
  {"id" : 3, "name" : "maria", "age": 13, "fruits": ["grappes", "blackberry"]}
  {"id" : 5, "name" : "camille", "age": 12, "fruits": ["cherry"]}
];

The real array I am using is very big this is why I am looking for the most efficient way of doing this.

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

0

You can use Array.prototype.reduce to group the objects.

const arr = [
  { id: 1, name: "john", age: 12, fruits: "banana" },
  { id: 2, name: "john", age: 12, fruits: "apple" },
  { id: 3, name: "maria", age: 13, fruits: "grappes" },
  { id: 4, name: "maria", age: 13, fruits: "blackberry" },
  { id: 5, name: "camille", age: 12, fruits: "cherry" },
];

const output = Object.values(
  arr.reduce((res, o) => {
    if (!res[o.name]) {
      res[o.name] = { ...o, fruits: [] };
    }
    res[o.name].fruits.push(o.fruits);
    return res;
  }, {})
);

console.log(output);

You can also write the above solution more succinctly:

const arr = [
  { id: 1, name: "john", age: 12, fruits: "banana" },
  { id: 2, name: "john", age: 12, fruits: "apple" },
  { id: 3, name: "maria", age: 13, fruits: "grappes" },
  { id: 4, name: "maria", age: 13, fruits: "blackberry" },
  { id: 5, name: "camille", age: 12, fruits: "cherry" },
];

const output = Object.values(
  arr.reduce(
    (res, o) => ((res[o.name] ||= { ...o, fruits: [] }).fruits.push(o.fruits), res),
    {}
  )
);

console.log(output);

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!