I have an array of objects like this:
let list = [
{
\'items\': [
\'item 1\',
\'item 2\'
]
},
{
\'items\': [
\'item 3\'
]
There are multiple ways you can achieve this:
const list = [{'items': ['item 1','item 2']},{'items': ['item 3']}]
// Using map and flat
console.log(list.map(o => o.items).flat())
// Using flatMap
console.log(list.flatMap(o => o.items))
// Using reduce
console.log(list.reduce((a, o) => a.concat(o.items), []))
// Using a plain old for loop (wrapped in a function)
const getItems = list => {
let temp = []
for (let i = 0; i < list.length; i++) {
const items = list[i].items
for (let j = 0; j < items.length; j++) {
temp.push(items[j])
}
}
return temp
}
console.log(getItems(list))
However, if you want a performance-first solution, reduce + for loop is the way to go:
const list = [{'items': ['item 1','item 2']},{'items': ['item 3']}]
console.log(list.reduce((a, o) => {
for (var i = 0; i < o.items.length; i++) a.push(o.items[i])
return a
}, []))
Check this jsperf for test cases.
You could use reduce()
. There is no way to avoid looping since Array prototype methods do loops internally
let list = [
{
'items': [
'item 1',
'item 2'
]
},
{
'items': [
'item 3'
]
}
];
const res = list.reduce((a,c) => [...a, ...c.items],[])
console.log(res)
https://lodash.com/docs/4.17.14#flatten
And
https://lodash.com/docs/4.17.14#flattenDeep
Look like they're exactly what you need.
you can use the Array.reduce method and follow the docs here
{
let list = [
{
'items': [
'item 1',
'item 2'
]
},
{
'items': [
'item 3'
]
}
];
/**
* @parameter {Array} arg
*/
function splat (arg) {
return arg.reduce((total, { items }) => [...total, ...items], []);
}
console.log(splat(list));
}
You could also play with recursive function to make a more generic function that accepts array of nested objects.
You can flat the map()
result using Array.prototype.flatMap():
The
flatMap()
method first maps each element using a mapping function, then flattens the result into a new array.
let list = [
{
'items': [
'item 1',
'item 2'
]
},
{
'items': [
'item 3'
]
}
]
list = list.flatMap(i => i.items);
console.log(list);