我有以下 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() :
The
flat()
method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
depth 是可选的
The depth level specifying how deep a nested array structure should be flattened. Defaults to 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);
关于javascript - 从数组中对象的数组中获取字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53079472/