javascript - 使用 es6 将对象中的对象中的值作为数组获取
问题描述
I'm pulling data from a service that loads into a dropdown and when a value is selected it's being assigned to a variable and an example is below
[{
"id": 482,
"firstName": "Micheal",
"lastName": "Bamford",
"email": "lalacifay@cliptik.net",
"areaCodes": [
{
"id": 60,
"name": "New York",
"status": "ACTIVE",
"createdDate": "2018-10-30 14:09:28"
},
{
"id": 12,
"name": "Florida",
"status": "ACTIVE",
"createdDate": "2018-10-30 14:09:28"
}
],
"createdDate": "2019-01-03 12:29:33"
}]
我想要实现的是只在这样的对象中获取name
属性areaCodes
['New York', 'Florida']
下面是我到目前为止使用的代码,它只让我得到数组中的第一个
const selected = this.listFromAPI.filter(t => t.id === ev.id).map(r=> r.areaCodes[0].name);
解决方案
这是你想要的?
const dataset = [{
"id": 482,
"firstName": "Micheal",
"lastName": "Bamford",
"email": "lalacifay@cliptik.net",
"areaCodes": [{
"id": 60,
"name": "New York",
"status": "ACTIVE",
"createdDate": "2018-10-30 14:09:28"
},
{
"id": 12,
"name": "Florida",
"status": "ACTIVE",
"createdDate": "2018-10-30 14:09:28"
}
],
"createdDate": "2019-01-03 12:29:33"
}];
for (const item of dataset) {
const {
areaCodes
} = item;
if (Array.isArray(areaCodes)) {
const names = areaCodes.map(c => c.name);
console.log(names);
}
}
推荐阅读
- sql - SQL ON DELETE CASCADE 基于条件
- vba - 如果 VBA 中的语句无法正常工作
- ios - openALPR 通过 Hyperloop 集成到 Appcelerator 应用程序中
- vba - 如何在用户表单中包含 msoFileDialogFolderPicker
- android - 无需 FCM/GCM 的 Android 永久通知服务
- r - 二项式混合效应模型 BIC - R 与 SPSS
- python - 安装 statsmodels - Python 3.6 32 位
- php - Laravel 5.5.20:找不到命令
- javascript - 在ejs中获取“未定义窗口”
- hibernate - 在@Column 中区分 b/w @NotNull 注释和可为空