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')
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.