我正在尝试比较,查找和推送数组内的数据。但是出现以下错误
错误=比;TypeError: undefined不是一个对象(求值'data[index].push')
有以下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"
}
]
我想将packages
对象推入匹配类别中,因此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",
"packages": [
{
"id":"abcds"
},
{
"id": "xyz"
}
]
}
]
下面是我试图做的代码:
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);
我不知道你的packages
数组是什么样子的,但这应该会给你预期的结果:
data.forEach((category, index) => { //data is main json/array in which I want to push packages
packages.forEach((pckg, idx) => {
if(category.package_id && pckg.identifier === category.package_id){
if (!category.packages) {
category.packages = [];
}
category.packages.push(pckg)
}
})
})
var packages = [
{
"id":"abcds"
},
{
"id": "xyz"
}
]
var categoryList = [
{
"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"
}
]
categoryList.forEach(x=>x.packages=[...packages]);