js lodash深度比较两个对象值 并输出相应key value
https://gist.github.com/Yimiprod/7ee176597fef230d1451
/**
* Deep diff between two object-likes
* @param {Object} fromObject the original object
* @param {Object} toObject the updated object
* @return {Object} a new object which represents the diff
*/
function deepDiff(fromObject, toObject) {
const changes = {};
const buildPath = (path, obj, key) =>
_.isUndefined(path) ? key : `${path}.${key}`;
const walk = (fromObject, toObject, path) => {
for (const key of _.keys(fromObject)) {
const currentPath = buildPath(path, fromObject, key);
if (!_.has(toObject, key)) {
changes[currentPath] = {from: _.get(fromObject, key)};
}
}
for (const [key, to] of _.entries(toObject)) {
const currentPath = buildPath(path, toObject, key);
if (!_.has(fromObject, key)) {
changes[currentPath] = {to};
} else {
const from = _.get(fromObject, key);
if (!_.isEqual(from, to)) {
if (_.isObjectLike(to) && _.isObjectLike(from)) {
walk(from, to, currentPath);
} else {
changes[currentPath] = {from, to};
}
}
}
}
};
walk(fromObject, toObject);
return changes;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
上次更新: 2023/09/17, 20:06:58