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

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

问题描述

我想比较2个数组对象在JavaScript中code。对象具有总共8个特性,但每个对象将不具有每一个值,并且该阵列被永远不会成为各任何大于8的物品,所以也许经过每个的蛮力方法,然后在寻找的值8特性就是做我想做的最简单的方法,但在实施之前,我想看看如果你有一个更好的解决方案。有什么想法?

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?

推荐答案

编辑:你不能重载运营商在JavaScript中跨preters的电流,常见的基于浏览器的实现。

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

要回答原来的问题,你可以做到这一点的一种方式,而且你要知道,这是一个黑客位,干脆的连载两个数组到JSON ,然后比较两个字符串JSON。这只会告诉你,如果数组是不同的,显然你能这样对的每个的数组中的对象,以及,看看哪些是不同的。

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.

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

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

编辑: 答案kamens了值得考虑为好,因为单一的功能来比较两个特定对象会比任何库小得多做,我建议什么(虽然我的建议肯定会工作不够好)。

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天全站免登陆