I have an array of nested objects, one of which looks like this (I've condensed the full object as it would be too large, jsonArr[0].data is where the objects will be):
var jsonArr = {
"data": [{
"id": 5201,
"name": "Simple Engineering",
"contracts": [{
"id": 461,
"contract_type_id": 99,
"contract_status_id": null,
"pivot": {
"entity_id": 5201,
"contract_id": 461
},
"projects": [{
"id": 2785,
"name": "Something Hydro",
"pivot": {
"contract_id": 461,
"project_id": 2785
}
}]
}]
}]
}
I have another array of values:
var ids = [461,452,478,655]
I am trying to figure out a way to match the values in ids to the values at data.contracts.id. If a value matches, then I want to retrieve data.name and projects.id.
So in this case, the result would be an array like below as only 461 matches:
var names = ["Simple Engineering",2785]
I hope this makes sense. As I am working with an array of several objects like the one above, I need a way that iterates over each ids value and each array object. Thanks, I appreciate any help.
var jsonArr = {
"data": [{
"id": 5201,
"name": "Simple Engineering",
"contracts": [{
"id": 461,
"contract_type_id": 99,
"contract_status_id": null,
"pivot": {
"entity_id": 5201,
"contract_id": 461
},
"projects": [{
"id": 2785,
"name": "Something Hydro",
"pivot": {
"contract_id": 461,
"project_id": 2785
}
}]
}]
}]
}
var ids = [461,452,478,655]
var names=[]
var matched = jsonArr.data?.map(d=>d?.contracts?.map(con=>con?.projects?.map(proj=>{
if(proj?.pivot?.contract_id===ids.find(id=>id===proj?.pivot?.contract_id))
{
names.push(d?.name)
names.push(proj?.pivot?.project_id)
}
})))
console.log(names)
var names=[]
var matched = jsonArr.map(jArr=>jArr?.data?.map(d=>d?.contracts?.map(con=>con?.projects?.map(proj=>{
if(proj?.pivot?.contract_id===ids.find(id=>id===proj?.pivot?.contract_id))
{
names.push(d?.name)
names.push(proj?.pivot?.project_id)
}
}))))
console.log(names)