javascript - javascript es6使用嵌套数组遍历对象的array,并返回单个 array?

106 4

考虑到以下场景,如何返回单个 array?

let array = [{
 name:"name01", 
 arr: [
 {name:"inner01"}, 
 {name:"inner02"}, 
 {name:"inner03"}
 ]
 }, {
 name:"name02", 
 arr: [
 {name:"inner04"}, 
 {name:"inner05"}, 
 {name:"inner06"}
 ]
 }
]
let convo = array.map(item => {
 return {
 name: item.name,
. . .item.arr,
 };
});

https://jsfiddle.net/3ng8dc2x/1/

我想得到一些类似的东西:

[
 {name:"name01"}, 
 {name:"inner01"}, 
 {name:"inner02"}, 
 {name:"inner03"},
 {name:"name02"},
 {name:"inner04"}, 
 {name:"inner05"}, 
 {name:"inner06"}
]

任何 direction 和所有的都非常感谢,所以请提前感谢 !

时间:

106 2

array reduce可能是一个更好的选择。

let array = [{
 name:"name01", 
 arr: [
 {name:"inner01"}, 
 {name:"inner02"}, 
 {name:"inner03"}
 ]
 }, {
 name:"name02", 
 arr: [
 {name:"inner04"}, 
 {name:"inner05"}, 
 {name:"inner06"}
 ]
 }
]
let convo = array.reduce((a, {name, arr}) => a.concat([{name}], arr), []);
console.log(convo)
原作者:
103 1

如果你是为最新的浏览器和最新的node 编写的,那么 flatMap() 插件是非常适合的:

let array = [{
 name:"name01", 
 arr: [
 {name:"inner01"}, 
 {name:"inner02"}, 
 {name:"inner03"}
 ]
 }, {
 name:"name02", 
 arr: [
 {name:"inner04"}, 
 {name:"inner05"}, 
 {name:"inner06"}
 ]
 }
]
let flat = array.flatMap(({name, arr}) => [{name},.. .arr])
console.log(flat)
97 5

你可以使用 reducedestructuring assignment

let array = [{name:"name01", arr: [{name:"inner01"}, {name:"inner02"}, {name:"inner03"}]},
{name:"name02", arr: [{name:"inner04"}, {name:"inner05"}, {name:"inner06"}]}]
let op = array.reduce((op,{name,arr}) =>op.concat([{name}],arr),[])
console.log(op)
...