簡體   English   中英

基於數組中不同位置的相同鍵合並對象

[英]Merge objects based on same key from different positions in an array

我有20個對象的2個數組,我想按名稱合並。 每個數組中名稱的順序是不同的,順序很重要,必須照原樣保留。 這使我無法采用傳統的排序和for循環方法。 基本上,我有:

var tempList1 = [
   {'manager':'John', 'x1':0, 'y1':0, 'x2':1, 'y2':1},
   {'manager':'Tom', 'x1':0, 'y1':50, 'x2':1, 'y2':1},
   {'manager':'Julie', 'x1':0, 'y1':80, 'x2':1, 'y2':1},
...
];

var tempList2 = [
   {'manager':'Tom', 'x3':0, 'y3':10, 'x4':1, 'y4':1},
   {'manager':'Julie', 'x3':0, 'y3':90, 'x4':1, 'y4':1},
   {'manager':'John', 'x3':0, 'y3':50, 'x4':1, 'y4':1},
...
];

請注意, John是在索引0tempList1但在指數2tempList2 當我嘗試:

          for (var k = 0; k < managerList.length; k++) {
            let merged = {...tempList1[k],...tempList2[k]}
            combinedList.push(merged);
          }

我犯了一個錯誤,即假設每個數組中的順序相同-當順序不同時。

最終結果應為:

var combinedList = [
    {'manager':'John', 'x1':0, 'y1':0, 'x2':1, 'y2':1, 'x3':0, 'y3':50, 'x4':1, 'y4':1},
    {'manager':'Tom', 'x1':0, 'y1':50, 'x2':1, 'y2':1, 'x3':0, 'y3':10, 'x4':1, 'y4':1},
    {'manager':'Julie', 'x1':0, 'y1':80, 'x2':1, 'y2':1, 'x3':0, 'y3':90, 'x4':1, 'y4':1}
];

如何合並對象,以便只有同一manager值的對象才能在數組中相互合並?

從其中一個列表中,創建一個由manager索引的對象。 然后,當遍歷其他列表時,只需查找相同的manager屬性並合並:

 var tempList1 = [ {'manager':'John', 'x1':0, 'y1':0, 'x2':1, 'y2':1}, {'manager':'Tom', 'x1':0, 'y1':50, 'x2':1, 'y2':1}, {'manager':'Julie', 'x1':0, 'y1':80, 'x2':1, 'y2':1} ]; var tempList2 = [ {'manager':'Tom', 'x3':0, 'y3':10, 'x4':1, 'y4':1}, {'manager':'Julie', 'x3':0, 'y3':90, 'x4':1, 'y4':1}, {'manager':'John', 'x3':0, 'y3':50, 'x4':1, 'y4':1} ]; const list1ByManager = tempList1.reduce((a, item) => { a[item.manager] = item; return a; }, {}); const combined = tempList2.map((item2) => ({ ...list1ByManager[item2.manager], ...item2 })); console.log(combined); 

由於每個管理需要一個案例,我將您的數組轉換為以經理名稱為鍵的對象,然后再次轉換為對象數組

 var tempList1 = [ {'manager':'John', 'x1':0, 'y1':0, 'x2':1, 'y2':1}, {'manager':'Tom', 'x3':0, 'y3':0, 'x4':1, 'y4':1}, {'manager':'Julie', 'x1':0, 'y1':0, 'x2':1, 'y2':1}, ].reduce(function(result, obj) { result[obj.manager] = obj return result }, {}); console.log(tempList1) var tempList2 = [ {'manager':'Tom', 'x3':0, 'y3':0, 'x4':1, 'y4':1}, {'manager':'Julie', 'x3':0, 'y3':0, 'x4':1, 'y4':1}, {'manager':'John', 'x3':0, 'y3':0, 'x4':1, 'y4':1}, ].reduce(function(result, obj) { result[obj.manager] = obj return result }, {}); var temp = [] for (var key in tempList1) { temp.push({ ...tempList1[key], ...tempList2[key] }) } console.log(temp) 

暫無
暫無

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

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