JavaScript(Lodash) - 两个对象的深度比较

时间:2017-02-01 14:17:04

标签: javascript

我们说我有两个深层对象:

var oldData = {
  "id": 1,
  "first_name": "Eric",
  "last_name": "Henry",
  "info": {
    "email": "ehenry0@smh.com.au",
    "gender": "Male",
    "ip_address": "7.11.169.150",
    "age": 11
  }
};

var newData = {
  "id": 2,
  "first_name": "Tommy",
  "last_name": "Henry",
  "info": {
    "email": "tommy@ghenrry.com",
    "gender": "Male",
    "ip_address": "7.11.169.150",
    "age": 15
  }
};

我如何使用lodash(或JavaScript)遍历每个对象并获取每个不同值的值,所以在最好的情况下它将是

[
   {old: 1, new: 2},
   {old: 'Eric', new: 'Tommy'},
   {old: 'ehenry0@smh.com.au', new: 'tommy@ghenrry.com'},
   {old: 11, new: 15},
]

这是我到目前为止所做的:



var oldData = {
  "id": 1,
  "first_name": "Eric",
  "last_name": "Henry",
  "info": {
    "email": "ehenry0@smh.com.au",
    "gender": "Male",
    "ip_address": "7.11.169.150",
    "age": 11
  }
};

var newData = {
  "id": 2,
  "first_name": "Tommy",
  "last_name": "Henry",
  "info": {
    "email": "tommy@ghenrry.com",
    "gender": "Male",
    "ip_address": "7.11.169.150",
    "age": 15
  }
};

var diffObj = _.difference(_.keys(oldData), _.keys(newData));

console.log(JSON.stringify(diffObj, null, 4));

<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

使用自定义递归函数compareUserDataObject.keys()函数的解决方案:

&#13;
&#13;
var oldData = { "id": 1, "first_name": "Eric", "last_name": "Henry", "info": { "email": "ehenry0@smh.com.au", "gender": "Male", "ip_address": "7.11.169.150", "age": 11 }
}; 
var newData = { "id": 2, "first_name": "Tommy", "last_name": "Henry", "info": { "email": "tommy@ghenrry.com", "gender": "Male", "ip_address": "7.11.169.150", "age": 15 }
};

function compareUserData(oldData, newData, result) {
    Object.keys(oldData).forEach(function (k) {
        if (typeof oldData[k] !== 'object') {
            if (oldData[k] != newData[k]) this.push({'old': oldData[k], 'new': newData[k]});
        } else {
            compareUserData(oldData[k], newData[k], this);
        }
    }, result);

    return result;
}

var result = compareUserData(oldData, newData, []);
console.log(result);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可能想要遍历对象属性,并手动检查是否有更改。 要了解如何迭代属性:Iterate through object properties

编辑:您的对象有嵌套属性,请阅读此文章以了解如何检查:How do I check if an object has a property in JavaScript?