2015-09-03 18 views
2

的兩個陣列之間的區別,它們之間的差別僅僅是補充,arrayAfter將有一個元素:找我有對象的兩個數組對象

var arrayBefore = [ 
    {"name":"Alan","height":"171","weight":"66"}, 
    {"name":"Ben","height":"182","weight":"90"} 
]; 

var arrayAfter= [ 
    {"name":"Alan","height":"171","weight":"66"}, 
    {"name":"Ben","height":"182","weight":"90"}, 
    {"name":"Chris","height":"163","weight":"71"} 
]; 

「名」永遠是獨一無二的!

如何找出哪一個是已添加的元素?我試過使用嵌套for循環結束,但這似乎過於複雜。

我也發現了這個好主意:

var diff = $(arrayAfter).not(arrayBefore).get(); 

然而,這似乎並沒有在對象上的數組工作正前方。

有沒有一些簡單的方法來獲得差異?

+2

您必須比較名稱,身高和體重以找出差異。沒有神奇的方法。 – tymeJV

+0

我想要一個jQuery解決方案,我知道這個名字將永遠是唯一的。 – peter

回答

2

如果只有名字所表示的唯一性,你可以這樣做:

//Get a list of all the names in the before array 
var beforeNames = arrayBefore.map(function(person) { return person.name }); 

//Filter the after array to only contain names not contained in the before array 
var uniqueObjects = arrayAfter.filter(function(person) { 
    return beforeNames.indexOf(person.name) === -1; 
}); 

console.log(uniqueObjects); //[{"name":"Chris","height":"163","weight":"71"}] 

演示:http://jsfiddle.net/tehgc8L5/

+0

非常酷,正是我所期待的,非常感謝。 – peter

+0

這工作正常,但請注意,對於大型數據集,數組查找('indexOf')將表現不佳。使用對象屬性應該可以加快速度:http://jsbin.com/nakugapoga/edit?js,console – GolfWolf

0

您可以使用Array.prototype.filter並過濾出前一個數組中的那些元素。

var differences = arrayAfter.filter(function(el) { 
    return arrayBefore.indexOf(el) === -1; 
}); 
+0

我誤解了這個問題嗎? –

+1

@Grimbode它適用於兩個數組都包含相同的對象實例。這是不是真的沒有說清楚。 –

+1

@MikeC他們有相同的數據,但不一樣,嘗試'({})===({})' – Hacketo

1

對於您可以Array.prototype.reduce()它迭代的對象鍵結合Array.prototype.filter()泛型方法:

arrayAfter.filter(function(after) { 
    return !arrayBefore.reduce(function(found, before) { 
     if (!found) { 
      found = true; 
      for (key in before) { 
       if (before.hasOwnProperty(key)) { 
        found = found && (before[key] === after[key]); 
       } 
      } 
     } 
     return found; 
    }, false); 
}); //[{name: "Chris", height: "163", weight: "71"}] 
0

我相信jQuery將有n這不會直接解決你的問題。你的問題是比較對象的平等。

我假設名稱是唯一的。如果沒有,對於這種方法,您將需要一個唯一的數據標識符。如果你絕對沒有,那麼你可以連接所有數據來獲得一個。

// first make a map of objects in before 
var before = {}; 
arrayBefore.forEach(function(o){ 
    before[o.name] = o; 
}); 

// now we get the elements of after that do not exist in our hashmap 
var result = arrayAfter.filter(function(o){ 
    return !(o.name in before); 
}); 

你可以很明顯地把它包裝在一個通用函數中。