在JavaScript中比较对象数组 [英] Comparing Arrays of Objects in JavaScript

查看:148
本文介绍了在JavaScript中比较对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较JavaScript代码中的2个对象数组。对象有8个总属性,但每个对象不会有每个对象的值,并且数组永远不会大于8个项目,所以也许粗暴的方法遍历每个,然后查看的值8属性是最简单的方法来做我想做的,但在实现之前,我想看看是否有人有一个更优雅的解决方案。任何想法?

解决方案

编辑:你不能重载操作符在当前,基于浏览器的JavaScript解释器的实现。

要回答原来的问题,你可以这样做,并且介意你,这是一个黑客,只是将两个数组序列化为JSON ,然后比较两个JSON字符串。这将简单地告诉你,如果数组是不同的,显然你可以这样做,以数组中的每个对象,以及看哪些是不同的。



另一个选择是使用一个库,它有一些不错的设施,用于比较对象 - 我使用和推荐 MochiKit

http://stackoverflow.com/questions/27030/comparing-arrays-of-objects-in-javascript#27932\">回答kamens给了也值得考虑,因为单个函数比较两个给定的对象将比任何图书馆小得多,我做的建议(虽然我的建议肯定会工作得很好)。



这里是一个天真的实施,可能只是为你做足够 - 请注意,此实现存在潜在问题:

  function objectsAreSame(x,y){
var objectsAreSame = true;
for(var propertyName in x){
if(x [propertyName]!== y [propertyName]){
objectsAreSame = false;
break;
}
}
return objectsAreSame;
}

假设两个对象都有完全相同的属性列表。 p>

哦,很明显,无论好坏,我都属于唯一一个回程的营地。 :)


I want to compare 2 arrays of objects in JavaScript code. The objects have 8 total properties, but each object will not have a value for each, and the arrays are never going to be any larger than 8 items each, so maybe the brute force method of traversing each and then looking at the values of the 8 properties is the easiest way to do what I want to do, but before implementing, I wanted to see if anyone had a more elegant solution. Any thoughts?

解决方案

EDIT: You cannot overload operators in current, common browser-based implementations of JavaScript interpreters.

To answer the original question, one way you could do this, and mind you, this is a bit of a hack, simply serialize the two arrays to JSON and then compare the two JSON strings. That would simply tell you if the arrays are different, obviously you could do this to each of the objects within the arrays as well to see which ones were different.

Another option is to use a library which has some nice facilities for comparing objects - I use and recommend MochiKit.


EDIT: The answer kamens gave deserves consideration as well, since a single function to compare two given objects would be much smaller than any library to do what I suggest (although my suggestion would certainly work well enough).

Here is a naïve implemenation that may do just enough for you - be aware that there are potential problems with this implementation:

function objectsAreSame(x, y) {
   var objectsAreSame = true;
   for(var propertyName in x) {
      if(x[propertyName] !== y[propertyName]) {
         objectsAreSame = false;
         break;
      }
   }
   return objectsAreSame;
}

The assumption is that both objects have the same exact list of properties.

Oh, and it is probably obvious that, for better or worse, I belong to the only-one-return-point camp. :)

这篇关于在JavaScript中比较对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆