我要迭代此数组,并且所有模型属性数组都应存储在单个数组中。
var arr = [{car:"Honda", model:["a","b","c"]},
{car:"Nissan", model:["a","b","c"]},
{car:"Chevrolet", model:["a","b","c"]},
]
答案 0 :(得分:1)
答案 1 :(得分:1)
关于Array.flatMap的事情是,它非常有用,但是在IE中没有完全的支持。
您也可以使用Array.reduce和ES6在一行中轻松完成所需的操作,如下所示:
var arr = [{car:"Honda", model:["a","b","c"]},{car:"Nissan", model:["a","b","c"]},{car:"Chevrolet", model:["a","b","c"]}]
let result = arr.reduce((r,{model}) => [...model, ...r], [])
console.log(result)
答案 2 :(得分:0)
使用flatMap
进行销毁:
var arr = [{car:"Honda", model:["a","b","c"]},{car:"Nissan", model:["a","b","c"]},{car:"Chevrolet", model:["a","b","c"]}];
const res = arr.flatMap(({ model }) => model);
console.log(res);
ES5语法:
var arr = [{car:"Honda", model:["a","b","c"]},{car:"Nissan", model:["a","b","c"]},{car:"Chevrolet", model:["a","b","c"]}];
var res = arr.map(function(item) {
return item.model;
}).reduce(function(acc, curr) {
return acc.concat(curr);
});
console.log(res);
如果要删除重复项,请使用Set
:
var arr = [{car:"Honda", model:["a","b","c"]},{car:"Nissan", model:["a","b","c"]},{car:"Chevrolet", model:["a","b","c"]}];
const res = [...new Set(arr.flatMap(({ model }) => model))];
console.log(res);