Today, we will be exploring how to group arrays of objects in JavaScript by ID. In this scenario, we have an array of IDs nested in an object of arrays (item3) that will be compared with another array of objects.
var existingArray = [
{
"item1": "Blah1",
"item2": "blah2",
"item3": ["0200","0300"],
"item4": "blah4",
"item5": "blah5"
},{
"item1": "Blah1",
"item2": "blah2",
"item3": ["0100","0300"],
"item4": "blah4",
"item5": "blah5"
},{
"item1": "Blah1",
"item2": "blah2",
"item3": ["0100"],
"item4": "blah4",
"item5": "blah5"
},{
"item1": "Blah1",
"item2": "blah2",
"item3": ["0300"],
"item4": "blah4",
"item5": "blah5"
},{
"item1": "Blah1",
"item2": "blah2",
"item3": ["0200", "0100"],
"item4": "blah4",
"item5": "blah5"
}
]
We now introduce our beloved DATA2 array which holds valuable information that we want to extract, specifically the "CandidateName" if the "relatedId" matches any of the IDs in item3 within EXISTINGARRAY.
var data2 = [
{"CandidateName": "Mary", "relatedId": ["0100", "0200"]},
{ "CandidateName": "John", "relatedId": ["0200"]},
{ "CandidateName":"Peter", "relatedId": ["0300", "0100"]},
{ "CandidateName": "Paul", "relatedId": ["0300"]}
];
The goal here is to search for matching IDs between data2[i].relatedId[j] and existingArray[k].item3[l], then extract the corresponding "CandidateName" and append it to EXISTINGARRAY. The end result should resemble the following:
existingArray = [
{
"item1": "Blah1",
"item2": "blah2",
"item3": ["0200","0300"],
"item4": "blah4",
"item5": "blah5",
"item6": ["Mary", "Jonh", "Peter", "Paul"]
},{
"item1": "Blah1",
"item2": "blah2",
"item3": ["0100","0300"],
"item4": "blah4",
"item5": "blah5",
"item6": ["Mary", "Peter", "Paul"]
},{
"item1": "Blah1",
"item2": "blah2",
"item3": ["0100"],
"item4": "blah4",
"item5": "blah5",
"item6": ["Mary", "Peter"]
},{
"item1": "Blah1",
"item2": "blah2",
"item3": ["0300"],
"item4": "blah4",
"item5": "blah5",
"item6": ["Peter", "Paul"]
},{
"item1": "Blah1",
"item2": "blah2",
"item3": ["0200", "0100"],
"item4": "blah4",
"item5": "blah5",
"item6": ["Mary", "John","Peter"]
}
]