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
JavaScript
x
19
19
1
[
2
{
3
"category":"Super",
4
"id":"1",
5
"images":[],
6
"status":"open",
7
"url":"some url here"
8
},
9
{
10
"category":"Pizza",
11
"entitlement_id":"pizza_pack_ent",
12
"id":"2",
13
"images":[],
14
"package_id":"pizza_pack_single",
15
"status":"locked",
16
"url":"some url here"
17
}
18
]
19
I want to push packages
object inside matching category so json/array will be as follows
JavaScript
1
27
27
1
[
2
{
3
"category":"Super",
4
"id":"1",
5
"images":[],
6
"status":"open",
7
"url":"some url here"
8
},
9
{
10
"category":"Pizza",
11
"entitlement_id":"pizza_pack_ent",
12
"id":"2",
13
"images":[],
14
"package_id":"pizza_pack_single",
15
"status":"locked",
16
"url":"some url here",
17
"packages": [
18
{
19
"id":"abcds"
20
},
21
{
22
"id": "xyz"
23
}
24
]
25
}
26
]
27
Following is the code what I was trying to do:
JavaScript
1
11
11
1
data.forEach((category, index) => { //data is main json/array in which I want to push packages
2
packages.forEach((pckg, idx) => {
3
if(pckg.identifier === category.package_id){
4
// data[category].push(pckg); //not worked
5
data[index].push(pckg); //not worked either
6
}
7
8
})
9
})
10
console.log(data);
11
Advertisement
Answer
I don’t know how your packages
array look like, but this should give you the expected result:
JavaScript
1
12
12
1
data.forEach((category, index) => { //data is main json/array in which I want to push packages
2
packages.forEach((pckg, idx) => {
3
if(category.package_id && pckg.identifier === category.package_id){
4
if (!category.packages) {
5
category.packages = [];
6
}
7
category.packages.push(pckg)
8
}
9
10
})
11
})
12