I have existing array and would like to add another object array to each item where the IDs match.
var existingData = [
{
"id": "0100",
"name": "name 1",
"message": [
"Lorem blah blah 1",
"Lorem blah blah 1.1"
]
},
{
"id": "0200",
"name": "name 2",
"message": [
"Lorem blah blah 2",
"Lorem blah blah 2.1",
"Lorem blah blah 2.2"
]
},
{
"id": "0300",
"name": "name 3",
"message": [
"Lorem blah blah 3",
"Lorem blah blah 3.1",
"Lorem blah blah 3.2",
"Lorem blah blah 3.3",
"Lorem blah blah 3.4"
]
}
];
and the following array is my second array in which the "relatedId" will be the same as the IDs in the existingArray:
var data2 = [
{"CandidateName": "Mary", "relatedId": ["0100", "0200"]},
{ "CandidateName": "John", "relatedId": ["0200"]},
{ "CandidateName":"Peter", "relatedId": ["0300", "0100"]},
{ "CandidateName": "Paul", "relatedId": ["0300"]}
];
If IDs match, I want to pull the "CandidateName" from data2 and put it into the existingData.
This particular question is has been extended from here => Group Javascript array of objects by ID
I have already made an attempt but I am not getting very far as the browser hangs:
var result = data.reduce(function(r, el) {
// THIS INNER LOOP MAKES THE BROWSER HANG!!!
data2.forEach(function (a){
console.log('a',a);
});
var e = el.id.slice(0, 2);
if (!o[e]) {
o[e] = {
id: el.id,
name: el.name,
message: []
}
r.push(o[e]);
}
o[e].message.push(el.message);
return r;
}, [])
So I want to end up with something like this:
var existingData = [
{
"id": "0100",
"name": "name 1",
"message": [
"Lorem blah blah 1",
"Lorem blah blah 1.1"
],
"CandidateName": ["Mary", "Peter"]
},
{
"id": "0200",
"name": "name 2",
"message": [
"Lorem blah blah 2",
"Lorem blah blah 2.1",
"Lorem blah blah 2.2"
],
"CandidateName": ["Mary", "John"]
},
{
"id": "0300",
"name": "name 3",
"message": [
"Lorem blah blah 3",
"Lorem blah blah 3.1",
"Lorem blah blah 3.2",
"Lorem blah blah 3.3",
"Lorem blah blah 3.4"
],
"CandidateName": ["Peter", "Paul"]
}
]