[英]Get string values from array in object that is in an array
I have the following JSON object: 我有以下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))));
What I want to do is, to get all types in an array. 我想要做的是,获取数组中的所有类型。 So the result should look like this:
所以结果应该是这样的:
['a', 'b', 'w', 't']
What I did: 我做了什么:
[].concat
.apply([], test.data.map(item => item.categories.map(el => el.type)))
I have the feeling that this could be done easier. 我觉得这可以更轻松。
Does someone know a better solution ? 有人知道更好的解决方案吗?
You can use Array.prototype.map() and Array.prototype.flat() : 您可以使用Array.prototype.map()和Array.prototype.flat() :
The
flat()
method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.flat()
方法创建一个新数组,所有子数组元素以递归方式连接到指定的深度。
Where depth is Optional 深度是可选的
The depth level specifying how deep a nested array structure should be flattened.
深度级别指定嵌套数组结构应该展平的深度。 Defaults to 1.
默认为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);
Use Array.reduce 使用Array.reduce
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'}]}]}; let result = test.data.reduce((a,c) => a.concat(c.categories.map(v => v.type)), []); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.