I am trying to merge the objects having same id and their corresponding array of objects having same value to that corresponding id of the object, which is nested inside the object. For example
[{
"id": "1",
"reference": "<p>test 1</p>",
"list": [
{
"text": "<p>text a</p>",
},
{
"text": "<p>text b</p>",
}
]},{
"id": "1",
"reference": "<p>test 1</p>",
"list": [
{
"text": "<p>text b</p>",
}
]},{
"id": "2",
"reference": "<p>test 2</p>",
"list": [
{
"text": "<p>test e</p>",
},
{
"text": "<p>text c</p>",
},
{
"text": "<p>text c</p>",
}
]},{
"id": "2",
"reference": "<p>test 2</p>",
"list": [
{
"text": "<p>test e</p>",
},
{
"text": "<p>text c</p>",
}
]},{
"id": "3",
"reference": "<p>test 3</p>",
"list": [
{
"text": "<p>text d</p>",
}
]}]
The expected result is
[{
"id": "1",
"reference": "<p>test 1</p>",
"list": [
{
"text": "<p>text a</p>",
},
{
"text": "<p>text b</p>",
}
]},{
"id": "2",
"reference": "<p>test 2</p>",
"list": [
{
"text": "<p>text c</p>",
},
{
"text": "<p>test e</p>",
}
]},{
"id": "3",
"reference": "<p>test 3</p>",
"list": [
{
"text": "<p>text d</p>",
}
]}]
I tried the following way, but didnot get the expected result. Dont know where I am going wrong.
Please dont recommend the use of .reduce()
.
const originalArray = [
{
"id": "1",
"reference": "<p>test 1</p>",
"list": [
{
"text": "<p>text a</p>",
},
{
"text": "<p>text b</p>",
}
]
},
{
"id": "1",
"reference": "<p>test 1</p>",
"list": [
{
"text": "<p>text b</p>",
}
]
},
{
"id": "2",
"reference": "<p>test 2</p>",
"list": [
{
"text": "<p>test e</p>",
},
{
"text": "<p>text c</p>",
},
{
"text": "<p>text c</p>",
}
]
},
{
"id": "2",
"reference": "<p>test 2</p>",
"list": [
{
"text": "<p>test e</p>",
},
{
"text": "<p>text c</p>",
}
]
},
{
"id": "3",
"reference": "<p>test 3</p>",
"list": [
{
"text": "<p>text d</p>",
}
]
}
];
var newArray = [];
var lookupObject = {};
for (var i in originalArray) {
lookupObject[originalArray[i]["id"]] = originalArray[i];
}
for (i in lookupObject) {
newArray.push(lookupObject[i]);
}
console.log(newArray)
question from:
https://stackoverflow.com/questions/65871452/how-to-merge-the-objects-having-same-id-and-corresponding-array-objects-which-ar