2016-09-19 74 views

回答

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 answerOriol's suggestion編輯在concat優化)

+0

這創建了太多的中間數組。更好地使用'[] .concat.apply([],Object.values(data))'或'[] .concat(... Object.values(data))' – Oriol

0

它看起來像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"] 

Fiddle

2

使用香草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>

使用_.flatMap()將在遍歷所有值的物體的因爲缺省迭代函數是簡單地_.identity()併產生一個單一的扁平所有這些數組。

+0

'concat(... arrayOfArrays)'is聰明,我完全錯過了這個優化。 +1 – ssube

相關問題