2014-10-30 139 views
0

我有一個包含某些重複的屬性對象的數組:以下是數組示例:陣列中的查找重複的對象值並將其合併 - JAVASCRIPT

var jsonData = [{x:12, machine1: 7}, {x:15, machine2:7},{x:12, machine2: 8}]; 

所以,我需要的是與合併的對象相同的x值如下面的數組:

var jsonData = [{x:12, machine1:7, machine2:8}, {x:15, machine2:7}] 

回答

0

我不知道,如果你正在尋找純JavaScript,但如果你是,這裏有一個解決方案。嵌套有點沉重,但它完成了工作。

// Loop through all objects in the array 
for (var i = 0; i < jsonData.length; i++) { 

    // Loop through all of the objects beyond i 
    // Don't increment automatically; we will do this later 
    for (var j = i+1; j < jsonData.length;) { 

    // Check if our x values are a match 
    if (jsonData[i].x == jsonData[j].x) { 

     // Loop through all of the keys in our matching object 
     for (var key in jsonData[j]) { 

     // Ensure the key actually belongs to the object 
     // This is to avoid any prototype inheritance problems 
     if (jsonData[j].hasOwnProperty(key)) { 

      // Copy over the values to the first object 
      // Note this will overwrite any values if the key already exists! 
      jsonData[i][key] = jsonData[j][key]; 
     } 
     } 

     // After copying the matching object, delete it from the array 
     // By deleting this object, the "next" object in the array moves back one 
     // Therefore it will be what j is prior to being incremented 
     // This is why we don't automatically increment 
     jsonData.splice(j, 1); 
    } else { 
     // If there's no match, increment to the next object to check 
     j++; 
    } 
    } 
} 

請注意,此示例中沒有防守代碼;您可能需要添加一些檢查以確保您傳遞的數據在傳遞之前已正確格式化。

也請記住,你可能必須決定如何處理,其中兩個鍵重疊,但兩者都做有machine1匹配(例如,兩個對象實例,但一個與5值和其他與價值9)。就像這樣,數組後面的任何對象都會優先。

+0

嘿謝謝噸,解決了這個問題:)目前的數據沒有同一臺機器的兩個實例,所以不應該是一個問題 – Ron 2014-10-31 00:05:39

1

我喜歡lodash庫。

https://lodash.com/docs#groupBy

_.groupBy(jsonData, 'x')生產:

12: [ {x=12, machine1=7}, {x=12, machine2=8} ], 
15: [ {x=15, machine2=7} ] 

你想要的結果達到這樣的:

var jsonData = [{x:12, machine1: 7}, {x:15, machine2:7},{x:12, machine2: 8}]; 
var groupedByX = _.groupBy(jsonData, 'x'); 
var result = []; 
_.forEach(groupedByX, function(value, key){ 
    var obj = {}; 
    for(var i=0; i<value.length; i++) { 
    _.defaults(obj, value[i]); 
    } 
    result.push(obj); 
}); 
+0

感謝您的幫助:) – Ron 2014-10-31 00:26:19

+0

任何人一個更簡單,更短的解決方案? ;) – angabriel 2014-10-31 00:37:06

0
const mergeUnique = (list, $M = new Map(), id) => { 
    list.map(e => $M.has(e[id]) ? $M.set(e[id], { ...e, ...$M.get(e[id]) }) : $M.set(e[id], e)); 
    return Array.from($M.values()); 
}; 

ID將是X,你的情況

我創建了一個jsperf與電子郵件作爲標識符:https://jsperf.com/mergeobjectswithmap/

它是快了很多:)