使用 angular6 从对象中删除子对象
2019-05-10
63
有一个 API 可以返回这样的数据
[
{
"id": 9,
"name": "Past Menu",
"serveDate": "2019-05-08 00:00:00",
"meals": [
{
"id": 27,
"name": "6",
"description": "6",
"image": "",
"mealType": "BREAKFAST",
"unitPrice": 6,
"status": "ENABLED"
},
{
"id": 28,
"name": "7",
"description": "7",
"image": "",
"mealType": "BREAKFAST",
"unitPrice": 7,
"status": "ENABLED"
},
{
"id": 30,
"name": "9",
"description": "9",
"image": "",
"mealType": "BREAKFAST",
"unitPrice": 9,
"status": "ENABLED"
}
]
},
{
"id": 8,
"name": "Bomb Menu",
"serveDate": "2019-05-10 00:00:00",
"meals": [
{
"id": 28,
"name": "7",
"description": "7",
"image": "",
"mealType": "BREAKFAST",
"unitPrice": 7,
"status": "ENABLED"
},
{
"id": 30,
"name": "9",
"description": "9",
"image": "",
"mealType": "BREAKFAST",
"unitPrice": 9,
"status": "ENABLED"
},
{
"id": 31,
"name": "10",
"description": "10",
"image": "",
"mealType": "BREAKFAST",
"unitPrice": 10,
"status": "ENABLED"
}
]
}
]
SERVICES
getMenus() {
this.dataServices.menuList(this.pagedData)
.subscribe(
response => {
if (response && response.code === HttpStatus.OK) {
this.dataList = response.data;
}
},
);
}
我目前正在尝试从服务器返回的数据中删除一个子对象,所以我有这个函数
deleteItem(item) {
for (let r = 0; r < this.dataList.meals.length; r++) {
if (this.dataList.meals[r].id === item.id) {
this.dataList.meals.splice(r, 1);
}
}
}
当我调用该函数时,我收到此错误
ERROR TypeError:无法读取未定义的属性“length”
2个回答
您需要浏览所有“菜单”项,然后过滤“餐点”项,如以下代码所示。
const dataList = [
{
"id": 9,
"name": "Past Menu",
"serveDate": "2019-05-08 00:00:00",
"meals": [
{
"id": 27,
"name": "6",
"description": "6",
"image": "",
"mealType": "BREAKFAST",
"unitPrice": 6,
"status": "ENABLED"
},
{
"id": 28,
"name": "7",
"description": "7",
"image": "",
"mealType": "BREAKFAST",
"unitPrice": 7,
"status": "ENABLED"
},
{
"id": 30,
"name": "9",
"description": "9",
"image": "",
"mealType": "BREAKFAST",
"unitPrice": 9,
"status": "ENABLED"
}
]
},
{
"id": 8,
"name": "Bomb Menu",
"serveDate": "2019-05-10 00:00:00",
"meals": [
{
"id": 28,
"name": "7",
"description": "7",
"image": "",
"mealType": "BREAKFAST",
"unitPrice": 7,
"status": "ENABLED"
},
{
"id": 30,
"name": "9",
"description": "9",
"image": "",
"mealType": "BREAKFAST",
"unitPrice": 9,
"status": "ENABLED"
},
{
"id": 31,
"name": "10",
"description": "10",
"image": "",
"mealType": "BREAKFAST",
"unitPrice": 10,
"status": "ENABLED"
}
]
}
];
function deleteItem(item) {
return dataList.map(menuItem => {
const newItem = {...menuItem};
newItem.meals = newItem.meals.filter(meal => meal.id !== item.id);
return newItem;
});
}
const newList = deleteItem({id:30});
console.log(JSON.stringify(newList,0,2));
return dataList.map(
浏览
菜单
项的外部列表,并允许返回修改后的值。
newItem.meals = newItem.meals.filter(meal => meal.id !== item.id);
浏览所有
餐点
项,如果您选择的 ID 与餐点 ID 匹配,则返回 false,在本例中为
30
。如果返回的值为 true,则
餐点
项将包含在过滤器中。否则将被排除。
Intervalia
2019-05-10
您应该在此上迭代:
680135961
Deyvid Martinez
2019-05-10