假设我有两个深层物体:
var oldData = {
"id": 1,
"first_name": "Eric",
"last_name": "Henry",
"info": {
"email": "[email protected]",
"gender": "Male",
"ip_address": "7.11.169.150",
"age": 11
}
};
var newData = {
"id": 2,
"first_name": "Tommy",
"last_name": "Henry",
"info": {
"email": "[email protected]",
"gender": "Male",
"ip_address": "7.11.169.150",
"age": 15
}
};
我将如何使用lodash(或JavaScript)遍历每个对象并获取每个不同值的值,因此在大写情况下
[
{old: 1, new: 2},
{old: 'Eric', new: 'Tommy'},
{old: '[email protected]', new: '[email protected]'},
{old: 11, new: 15},
]
这是我到目前为止的内容:
var oldData = {
"id": 1,
"first_name": "Eric",
"last_name": "Henry",
"info": {
"email": "[email protected]",
"gender": "Male",
"ip_address": "7.11.169.150",
"age": 11
}
};
var newData = {
"id": 2,
"first_name": "Tommy",
"last_name": "Henry",
"info": {
"email": "[email protected]",
"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>
使用自定义递归函数compareUserData
和Object.keys()
函数的解决方案:
var oldData = { "id": 1, "first_name": "Eric", "last_name": "Henry", "info": { "email": "[email protected]", "gender": "Male", "ip_address": "7.11.169.150", "age": 11 }
};
var newData = { "id": 2, "first_name": "Tommy", "last_name": "Henry", "info": { "email": "[email protected]", "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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句