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.