I have the following JSON object:
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():
The
flat()method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
Where depth is Optional
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);
Use 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With