我想要做的就是採取的物體,像lodash或vanilla JS有一個很好的方法來將數組中的對象平鋪到數組中嗎?
{ SomeKey: [A, B, C],
SomeOtherKey: [D],
AndAnother: [E, F] }
並使其成爲
[ A, B, C, D, E, F ]
我沒有看到the documentation任何不錯的方式,但也許它在衆目睽睽下從我藏身。
我想要做的就是採取的物體,像lodash或vanilla JS有一個很好的方法來將數組中的對象平鋪到數組中嗎?
{ SomeKey: [A, B, C],
SomeOtherKey: [D],
AndAnother: [E, F] }
並使其成爲
[ A, B, C, D, E, F ]
我沒有看到the documentation任何不錯的方式,但也許它在衆目睽睽下從我藏身。
如果你在最新一代瀏覽器,你可以使用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
優化)
它看起來像lodash 做到這一點。
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"]
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>
使用_.flatMap()
將在遍歷所有值的物體的因爲缺省迭代函數是簡單地_.identity()
併產生一個單一的扁平所有這些數組。
'concat(... arrayOfArrays)'is聰明,我完全錯過了這個優化。 +1 – ssube
這創建了太多的中間數組。更好地使用'[] .concat.apply([],Object.values(data))'或'[] .concat(... Object.values(data))' – Oriol