进行“Diff”操作在 javascript / jQuery 中的关联数组上?
如果我有两个关联数组,对它们的值进行比较的最有效方法是什么?
例如,给定:
array1 = {
foreground: 'red',
shape: 'circle',
background: 'yellow'
};
array2 = {
foreground: 'red',
shape: 'square',
angle: '90',
background: 'yellow'
};
我如何检查一个与另一个,这样缺少或附加的项目就是结果数组。在这种情况下,如果我想在 array2 中比较 array1,它将返回:
array3 = {shape: 'circle'}
而如果我在 array1 中比较 array2,它将返回:
array3 = {shape: 'square', angle: '90'}
提前感谢您的帮助!
If I have two associative arrays, what would be the most efficient way of doing a diff against their values?
For example, given:
array1 = {
foreground: 'red',
shape: 'circle',
background: 'yellow'
};
array2 = {
foreground: 'red',
shape: 'square',
angle: '90',
background: 'yellow'
};
How would I check one against the other, such that the items missing or additional are the resulting array. In this case, if I wanted to compare array1 within array2, it would return:
array3 = {shape: 'circle'}
Whilst if I compared array2 within array1, it would return:
array3 = {shape: 'square', angle: '90'}
Thanks in advance for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
试试这个:
Try this:
如果您熟悉 PHP 语法,请查看 http://phpjs.org/functions/index 其中包括几乎所有转换为 JavaScript 的 PHP 数组相关函数 - 包括
array_diff
< /a>If you're familiar with PHP syntax, take a look at http://phpjs.org/functions/index which includes almost all PHP's array related functions converted into JavaScript – including
array_diff
RaYell 的解决方案很好,但不幸的是只会告诉你 obj2 中与 obj1 不同或不存在的项,如果我们需要知道两边,让我们获取所有键然后进行比较。以下函数将返回一个关联数组,其中包含每个对象的键值。哦...公平地说,我还没有测试过,但这应该有效。
哦,虽然我确实认识到第一个解决方案回答了最初的问题,但我认为上述解决方案提供了另一种方法,初始用户可能会发现有用,以便不需要检查两次。
RaYell's solution is nice but unfortunately will only tell you the items in obj2 that are either different from or non-existant in obj1, if we need to know both sides, let's get all keys and then compare. The following function will return an associative array with key values for each object. Oh... to be fair, I haven't tested yet, but this should work.
Oh, and while I do recognize that the first solution answered the initial question, I think the above solution offers another approach that the initial user might find useful so as to not require checking twice.
这可能比您需要的复杂得多,但您可以尝试我的 jsondiffpatch lib,它将区分任何一对 javascript 对象:
https://github.com/benjamine/jsondiffpatch
如果你想测试它,你可以在 http://benjamine.github.com/jsondiffpatch/demo/index.html
This might be much more sophisticate than what you need, but you can try my jsondiffpatch lib that will diff any pair of javascript objects:
https://github.com/benjamine/jsondiffpatch
if you want to test it you can see it live in http://benjamine.github.com/jsondiffpatch/demo/index.html
明哈榕阿西姆:
A minha ficou assim: