javascript - 从数组中的对象中的数组中获取字符串值
问题描述
我有以下 JSON 对象:
var test = {
data: [{
itemID: 0,
categories: [{
id: 0,
type: 'a',
name: 'world'
}, {
id: 1,
type: 'b',
name: 'plants'
}]
},
{
itemID: 1,
categories: [{
id: 2,
type: 'w',
name: 'cars'
}, {
id: 3,
type: 't',
name: 'bicycles'
}]
}
]
};
console.log([].concat
.apply([], test.data.map(item => item.categories.map(el => el.type))));
我想要做的是,获取数组中的所有类型。所以结果应该是这样的:
['a', 'b', 'w', 't']
我做了什么:
[].concat
.apply([], test.data.map(item => item.categories.map(el => el.type)))
我觉得这可以更容易地完成。
有人知道更好的解决方案吗?
解决方案
您可以使用Array.prototype.map()和Array.prototype.flat():
该
flat()
方法创建一个新数组,其中所有子数组元素递归连接到指定深度。
深度是可选的
指定嵌套数组结构应该展平的深度级别。默认为 1。
var test = {
data: [{
itemID: 0,
categories: [{
id: 0,
type: 'a',
name: 'world'
}, {
id: 1,
type: 'b',
name: 'plants'
}]
},
{
itemID: 1,
categories: [{
id: 2,
type: 'w',
name: 'cars'
}, {
id: 3,
type: 't',
name: 'bicycles'
}]
}
]
};
var type = test.data.map(item => item.categories.map(el => el.type)).flat();
console.log(type);
推荐阅读
- c - 编译错误指纹
- highcharts - 在 Vue 中使用 HTML 或如何使其适应 Vue.js
- algorithm - 生成一个包含所有可能替换的列表
- python - 在 Anaconda 中使用 Python 3.6.4 的 Tensorflow 1.8.0 显示错误 _dataset_ops.so 未找到
- r - R:使用 dplyr 创建具有每组百分比的数据框
- mysql - 将外部 sql 文件加载到存储过程中
- javascript - 浏览器、时区、Chrome 67 错误(历史时区更改)
- presto - Presto:前一个月的最后一天
- amazon-web-services - 是否可以在 AWS cloudformation 中提供非 base64 字符串作为输入
- node.js - 从 Feathers nedb 迁移到 Postgres 需要对代码进行哪些更改?