I have an array of objects that I need to manipulate by combining entries with the same key/values for 'name' and 'size'. Here is the original array:
[
{
id: 1,
name: "foo",
size: 4998,
relatedId: 17,
link: "https://www.google.com/"
},
{
id: 2,
name: "foo",
size: 4998,
relatedId: 21,
link: "https://www.google2.com/"
},
{
id: 3,
name: "bar",
size: 381,
relatedId: 35,
link: "https://www.google3.com/"
},
{
id: 4,
name: "bar",
size: 381,
relatedId: 41,
link: "https://www.google4.com/"
},
{
id: 5,
name: "baz",
size: 666,
relatedId: 50,
link: "https://www.google5.com/"
},
]
The desired output should look like this:
[
{
id: 1,
name: "foo",
size: 4998,
relatedId: 17,
link: "https://www.google.com/",
relations: [
{
id: 1,
relatedId: 17
},
{
id: 2,
relatedId: 21
}
]
},
{
id: 3,
name: "bar",
size: 381,
relatedId: 35,
relations: [
{
id: 3,
relatedId: 35
},
{
id: 4,
relatedId: 41
}
]
},
{
id: 5,
name: "baz",
size: 666,
relatedId: 50,
relations: [
{
id: 5,
relatedId: 50
}
]
}
]
To achieve this, a new property called relations needs to be added to the objects. If multiple objects share the same name and size, all but the first entry should be removed and their id and relatedId pushed to the relations array.
Here is the attempted function that has not worked as expected yet:
mergeDuplicates (fileArray) {
for (let i = 0; i < fileArray.length; i++) {
fileArray[i].relations = []
fileArray[i].relations.push({
id: fileArray[i].id,
relatedId: fileArray[i].relatedId,
})
for (let j = 1; j < fileArray.length; j++) {
if (fileArray[i].name === fileArray[j].name && fileArray[i].size === fileArray[j].size) {
fileArray[i].relations.push({
id: fileArray[j].id,
relatedId: fileArray[j].relatedId,
})
fileArray.splice(j, 1)
}
}
}
return fileArray;
}