![](/img/trans.png)
[英]I have an 'n' number of array and how can I concat all array into a single array using jQuery
[英]Concat n numbers of array into a single array
假設我有一個對象,它的值是這樣的數組:
obj = {
'key1': [1,2],
'key2': [3,4],
'key3': [5,6],
}
如何使用 concat 將對象的所有數組合並為一個數組。 對象的鍵數當然是動態的,但它至少會有一個實例所需的輸出是這樣的:
[1,2,3,4,5,6]
Object.values()
flat()
上的Object.values()
應該完成這項工作:
const obj = { key1: [1,2], key2: [3,4], key3: [5,6] }, merged = Object.values(obj).flat() console.log(merged)
.as-console-wrapper{min-height:100%}
如果不幸無法處理 IE 或 Edge,則可能會回退到reduce()
以進行展平:
const obj = { key1: [1,2], key2: [3,4], key3: [5,6] }, merged = Object.keys(obj).reduce(function(r,k){ return r.concat(obj[k]) }, []) console.log(merged)
.as-console-wrapper{min-height:100%}
var obj={ 'key1': [1,2], 'key2': [3,4], 'key3': [5,6] };
var result = Object.values(obj)
.reduce((accum, values) => {
accum.push(...values);
return accum;
}, []);
console.log(result);
如果你假設對象的所有值都是一個數組,你可以創建一個Object.values()
循環並連接每個數組。
const obj={
'key1': [1,2],
'key2': [3,4],
'key3': [5,6],
};
const res = [];
for (const value of Object.values(obj)) {
res.push(...value);
}
/// res: [1,2,3,4,5,6]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.