簡體   English   中英

將多個對象 arrays 合並為一個對象數組 JavaScript

[英]Merge multiple arrays of objects into one array of objects JavaScript

所以假設我有幾個不同的 Arrays 如下:

var first = [{key1: x},{key1:y},{key1:z},{key1:a},{key1:b},{key1:v}, ...];
var second = [{key2: anything},{key2:...},{key2:...},{key2:...},{key2:...},{key2:...}, ...];
var third = [{key3: value},{key3:...},{key3:...},{key3:...},{key3:...},{key3:...}, ...];
var fourth = [{key4:another value},{key4:...},{key4:...},{key4:...},{key4:...},{key4:...}];
var fifth = [{key5: and another one},{key5:...},{key5:...},{key5:...},{key5:...},{key5:...}];
.
.
.
and so on...

現在我想將它們合並到一個數組中,其中我的新對象包含其他 arrays 中的每一個,如下所示:

var newBigArray = [{key1: x, key2: anything, key3: value, key4: another value, key5: and another one (here in this object the first of each of the original array's objects merged into one},{here in the second object the second of each of the original array's objects...},{here the third...},{fourth},{fifth},{...},...];

我希望你能明白。

我已經嘗試過.push()方法、 Object.assign()以及 for 循環的一些變體,但我找不到解決方案。

一個 go 怎么會這樣,有什么想法嗎?

您可以收集數組中的所有對象並將同一索引的所有屬性分配給單個 object。

 const first = [{ key1: 'a' }, { key1: 'b' }, { key1: 'c' }, { key1: 'd' }, { key1: 'e' }, { key1: 'f' }], second = [{ key2: 1 }, { key2: 2 }, { key2: 3 }, { key2: 4 }, { key2: 5 }, { key2: 6 }], third = [{ key3: 'z' }, { key3: 'y' }, { key3: 'x' }, { key3: 'w' }, { key3: 'v' }, { key3: 'u' }], result = [first, second, third].reduce((r, a) => a.map((o, i) => Object.assign(r[i] || {}, o)), []); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

您可以使用擴展運算符:

 let first = [{x: 1, y:2}] let second = [{x: 2, y:2}] let third = [{x: 3, y:2}] let fourth = [{x: 4, y:2}] let fifth = [{x: 5, y:2}] let finalArray = [...first, ...second, ...third, ...fourth, ...fifth ] console.log(finalArray)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM