我想在数组下面显示所有模型属性值在一个数组中

时间:2019-05-13 04:07:52

标签: javascript arrays object

我要迭代此数组,并且所有模型属性数组都应存储在单个数组中。

var arr = [{car:"Honda", model:["a","b","c"]},
       {car:"Nissan", model:["a","b","c"]},
       {car:"Chevrolet", model:["a","b","c"]},
      ]

3 个答案:

答案 0 :(得分:1)

您可以使用flatMap()并在model中返回arr的{​​{1}}属性

flatMap()

答案 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);