做一个“差异"在 javascript/jQuery 中的关联数组上? [英] Doing a "Diff" on an Associative Array in javascript / jQuery?

查看:32
本文介绍了做一个“差异"在 javascript/jQuery 中的关联数组上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个关联数组,比较它们的值的最有效方法是什么?

If I have two associative arrays, what would be the most efficient way of doing a diff against their values?

例如,给定:

  array1 = {
    foreground: 'red',
    shape: 'circle',
    background: 'yellow'
  };

  array2 = {
    foreground: 'red',
    shape: 'square',
    angle: '90',
    background: 'yellow'
  };

我将如何检查一个与另一个,使得 missing additional 的项目是结果数组.在这种情况下,如果我想比较 array2 中的 array1,它将返回:

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'}

如果我在 array1 中比较 array2,它会返回:

Whilst if I compared array2 within array1, it would return:

array3 = {shape: 'square', angle: '90'}

预先感谢您的帮助!

推荐答案

试试这个:

function diff(obj1, obj2) {
    var result = {};
    $.each(obj1, function (key, value) {
        if (!obj2.hasOwnProperty(key) || obj2[key] !== obj1[key]) {
            result[key] = value;
        }
    });

    return result;
}

这篇关于做一个“差异"在 javascript/jQuery 中的关联数组上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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