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

142
Views
If object property have same id, push into new array

I would like to push the names into an new object if they have the same Id. The solution is not there yet, but I'm getting closer

const names = [
{id:1,name:"jame"},
{id:2,name:"jill"},
{id:3,name:"hanna"},
{id:3,name:"clark"}
]

const newNames = []
// Something like this
names.foreach((person,index) => {
 if(newNames[index].id === person.id){
 newNames.push({id:person.index, names:[...newNames.name,person.name]})
 }else{
 newNames.push({id:person.index, person.name})
 }
})

The outcome would look something like this:

const newNames = [
{id:1,name:"jame"},
{id:2,name:"jill"},
{id:3,names: {name:"clark",name:"hanna"}}
]

Issue: Cannot read properties of undefined (reading 'id')

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

0

One way to do it:

const names = [
    {id:1,name:"jame"},
    {id:2,name:"jill"},
    {id:3,name:"hanna"},
    {id:3,name:"clark"}
];

let output = []
let ids = [...new Set(names.map(i=>i.id))];
ids.forEach((id) => {
    let res = names.filter((name) => name.id == id)
    output.push({id, name: res.length > 1 ?
        res.map(i => i.name) :
        res[0].name})
})
console.log(output)

Note I have given an array for the name attribute for entries with multiple names to be less repetitive.


Going along with your solution:

names.forEach((person,index) => {
    let existingIndex = newNames.findIndex( (entry) => entry.id === person.id)
    if(existingIndex >= 0){
        if(newNames[existingIndex].hasOwnProperty('name'))
            newNames[existingIndex] = ({id: person.id, names: [newNames[existingIndex].name,person.name]})
        else
            newNames[existingIndex] = ({id: person.id, names: [...newNames[existingIndex].names,person.name]})
     } else {
        newNames.push({id:person.id, name: person.name})
      }
})

The part newNames[index].id in your original solution results in an error because newNames does not have any elements so far. So basically newNames[0] results in undefined.

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!