lodash或vanilla JS有一种很好的方法可以将数组对象展平成数组吗?

时间:2016-09-19 19:43:48

标签: javascript lodash

我想做的是拿一个像

这样的对象
{  SomeKey: [A, B, C], 
   SomeOtherKey: [D], 
   AndAnother: [E, F]  }

并将其变为

[ A, B, C, D, E, F ]

我在the documentation中没有看到任何好的方式,但也许它隐藏在我的视线之内。

3 个答案:

答案 0 :(得分:4)

如果您使用的是最新一代浏览器,则可以使用Object.values,这听起来完全正确:



const data = {
  SomeKey: ['A', 'B', 'C'],
  SomeOtherKey: ['D'],
  AndAnother: ['E', 'F']
};

const out = [].concat(...Object.values(data));

console.log(out);




如果您使用的是较旧的浏览器(回到IE9),Object.keys仍然非常接近:



const data = {
  SomeKey: ['A', 'B', 'C'],
  SomeOtherKey: ['D'],
  AndAnother: ['E', 'F']
};

const out = [].concat(...Object.keys(data).map(key => data[key]));

console.log(out);




(来自vlaz's answer编辑的Oriol's suggestionconcat优化)

答案 1 :(得分:2)

使用vanilla JS



var input = {  
   SomeKey: ["A", "B", "C"], 
   SomeOtherKey: ["D"], 
   AndAnother: ["E", "F"]  
};

var outputES5 = Object.keys(input).reduce(function (memo, key) {
  return memo.concat(input[key])
}, []);

//Using ES6 fat arrow function
 const outputES6 = Object.keys(input).reduce(
  (memo, key) => memo.concat(input[key]),
   []
);

//Using Object.values and the spread operator
const outputES6Values = [].concat(...Object.values(input));

console.log("ES5 reduce", outputES5);
console.log("ES6 reduce and fat arrow function", outputES6);
console.log("ES6 Object.values and spread operator", outputES6Values);




Array.prototype.reduce()

Object.keys()

Object.values() - 注意:目前尚未得到广泛支持。

Spread operator (...)

使用Lodash



var input = {  
   SomeKey: ["A", "B", "C"], 
   SomeOtherKey: ["D"], 
   AndAnother: ["E", "F"]  
};

var output = _.flatMap(input);

console.log(output);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.0/lodash.min.js"></script>
&#13;
&#13;
&#13;

使用_.flatMap()将遍历对象的所有,因为默认迭代函数只是_.identity()并生成所有这些的扁平数组。

答案 2 :(得分:0)

看起来像lodash _.flatMap这样做。

https://lodash.com/docs/4.16.0#flatMap

var data = {
  SomeKey: ['A', 'B', 'C'],
  SomeOtherKey: ['D'],
  AndAnother: ['E', 'F']
};

console.log(_.flatMap(data)); //["A", "B", "C", "D", "E", "F"] 

Fiddle