Is there a way to search for a specific value in an array and if it exists, then add another value into a different array?
I have two large arrays: one containing people and the other containing blogs. I want to accomplish this using JavaScript. Here is a simplified example of my arrays:
arr2 = [
{
"post_title": "In-House Counsel’s Role in Optimizing Intellectual Property",
"post_date": "@1667970000",
"custom": {
"author": [
{
"type": "attorney",
"identifier": "Deborah Stehr"
}
]
}
},
// Additional objects from arr2 ...
]
arr1 = [
{
"post_title": "Deborah Stehr",
"custom": {
"title": "Senior Counsel"
}
},
// Additional objects from arr1 ...
]
I aim for the arr1 array to output the following after manipulation:
[
{
"post_title": "Deborah Stehr",
"custom": {
"title": "Senior Counsel",
"related_posts": [
{
"type": "blog",
"identifier": "In-House Counsel’s Role in Optimizing Intellectual Property"
},
// Additional related posts for Deborah Stehr ...
]
}
},
// Additional transformed objects from arr1 ...
]
This is the approach I took but it only captures the first object from arr2:
for(var i=0; i < arr2.length; i++){
if(arr2[i].custom.author[0].identifier == 'Deborah Stehr'){
for(var t=0; t < arr1.length; t++){
if(arr1[t].post_title == 'Deborah Stehr'){
arr1[t].custom.related_posts = [];
arr1[t].custom.related_posts.push({
"type": "blog",
"identifier": arr2[i].post_title
})
}
}
}
}
// Addition of similar loops for other authors...
The current implementation works but only handles the first object from arr2. How can I loop through both arrays to achieve the desired outcome?