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

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

问题描述

我想比较 JavaScript 代码中的 2 个对象数组.这些对象总共有 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 解释器的当前常见的基于浏览器的实现中重载运算符.

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 给出的答案a> 也值得考虑,因为用于比较两个给定对象的单个函数将比执行我建议的任何库都要小得多(尽管我的建议肯定会工作得很好).

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