gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:54:36 25 4
gpt4 key购买 nike

假设我有两个深层对象:

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>

最佳答案

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

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);

关于JavaScript (Lodash) - 两个对象的深度比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41981969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com