I am trying to compare, find and push data inside an array. But getting following error
Error => TypeError: undefined is not an object (evaluating 'data[index].push')
I have following JSON/Array
[
{
"category":"Super",
"id":"1",
"images":[],
"status":"open",
"url":"some url here"
},
{
"category":"Pizza",
"entitlement_id":"pizza_pack_ent",
"id":"2",
"images":[],
"package_id":"pizza_pack_single",
"status":"locked",
"url":"some url here"
}
]
I want to push packages object inside matching category so json/array will be as follows
[
{
"category":"Super",
"id":"1",
"images":[],
"status":"open",
"url":"some url here"
},
{
"category":"Pizza",
"entitlement_id":"pizza_pack_ent",
"id":"2",
"images":[],
"package_id":"pizza_pack_single",
"status":"locked",
"url":"some url here",
"packages": [
{
"id":"abcds"
},
{
"id": "xyz"
}
]
}
]
Following is the code what I was trying to do:
data.forEach((category, index) => { //data is main json/array in which I want to push packages
packages.forEach((pckg, idx) => {
if(pckg.identifier === category.package_id){
// data[category].push(pckg); //not worked
data[index].push(pckg); //not worked either
}
})
})
console.log(data);
datais an array of objects, sodata[index]will be an object. You can't push to an object.packageproperty on that object with an empty array (if not existing) and push to thatif(pckg.identifier === category.package_id)might unexpectedly returntrueif both thepckg.identifierandcategory.package_idare undefined. So if you have categories where thepackage_idis missing (such as the first element in your example array), you may want to address that as well.