如何找到两个JavaScript对象数组之间的差异? [英] How to find differences between two JavaScript arrays of objects?

查看:96
本文介绍了如何找到两个JavaScript对象数组之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个JavaScript数组 orig (原始对象数组)和 update (更新后的原始数组)对象)具有相同的长度并包含对象,我想输出每对对象之间的差异。

I have two JavaScript arrays orig (the original array of objects) and update (the updated orig array of objects) that have the same length and contain objects, and I want to output the differences between the each pair of objects.

示例:

var orig = [{enabled:"true", name:"Obj1", id:3},{enabled:"true", name:"Obj2", id:4}]; 

var update = [{enabled:"true", name:"Obj1", id:3}, {enabled:"true", name:"Obj2-updated", id:4}];

输出应为:名称:Obj2-updated

我实施了一些但需要优化...

I implemented something but it needs optimization...

for(var prop=0; prop<orig.length; prop++) {
  for(prop=0; prop<update.length; prop++) {
    if(orig[prop].enabled != update.enabled) { console.log(update.enabled) }
    if(orig[prop].name != update[prop].name) { console.log(update[prop].name) }
    if(orig[prop].id != update[prop].id) { console.log(update[prop].id) }
  }
}


推荐答案

您可以过滤密钥并使用更新后的密钥获取结果集。

You could filter the keys and get a result set with the updated keys.

var orig = [{ enabled: "true", name: "Obj1", id: 3 }, { enabled: "true", name: "Obj2", id: 4 }],
    update = [{ enabled: "true", name: "Obj1", id: 3 }, { enabled: "true", name: "Obj2-updated", id: 4 }],
    difference = [];

orig.forEach(function (a, i) {
    Object.keys(a).forEach(function (k) {
        if (a[k] !== update[i][k]) {
            difference.push({ id: update[i].id, key: k, value: update[i][k], index: i });
        }
    });
});

console.log(difference);

这篇关于如何找到两个JavaScript对象数组之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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