将数据推送到数组索引内。React Native JSX
2021-09-24
1046
我尝试比较、查找和推送数组内的数据。但出现以下错误
Error => TypeError: undefined is not an object (evaluating '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);
2个回答
我不知道您的
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)
}
})
})
lbsn
2021-09-24
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]);
MohitFBorse
2021-09-24