首页 > 解决方案 > 用户点击 angular6 后获取所有子对象 ID 的列表

问题描述

我正在页面上显示来自 API 的记录列表。该页面同时显示父对象和子对象。

JSON数据

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": "Good 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"
      }
    ]
  }
];

HTML 视图

<div *ngFor="let item of menuList">
    <h2 (click)="getMealsIds()">Menu</h2>
    {{item.name}} - {{item.servedate}}
  <h2>Meals</h2>
    <div *ngFor="let meal of item.meals">
        <span (click)="removeMeal(meal, item.id)">{{meal.name}} - {{meal.mealType}}</span>
    </div>
</div>

现在我想要实现的是,当单击特定菜单时,我应该能够获取数组中的所有餐点 ID

功能

getMealsIds(parent) {
console.log(parent.meals.id)
}

有关如何使这项工作正常进行的任何帮助?使用我当前的脚本单击时出现未定义的错误

标签: javascriptangular

解决方案


你想要map的数组。如果parentdataList[0]那么

console.log(parent.meals.map(m => m.id)); // [27, 28, 30]

推荐阅读