我想做的是拿一个像
这样的对象{ SomeKey: [A, B, C],
SomeOtherKey: [D],
AndAnother: [E, F] }
并将其变为
[ A, B, C, D, E, F ]
我在the documentation中没有看到任何好的方式,但也许它隐藏在我的视线之内。
答案 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 suggestion的concat
优化)
答案 1 :(得分:2)
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);

Object.values() - 注意:目前尚未得到广泛支持。
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;
使用_.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"]