I’ve 2 Objects with data that is repeated but also varies. How to compare them and get the differences?
JavaScript
x
18
18
1
const obj1 = {
2
surname: "kowalski",
3
name: "adam",
4
age: 23,
5
city: "Wroclaw",
6
country: "Poland",
7
};
8
9
const obj2 = {
10
name: "adam",
11
age: 34,
12
city: "Warszawa",
13
country: "Poland",
14
friend: "Ala",
15
};
16
17
const objCombined = { obj1, obj2 };
18
I’ve to use .reduce
.
My work:
JavaScript
1
8
1
const find = Object.entries(objCombined).reduce((diff, [key]) => {
2
if (!obj2[key]) return diff;
3
4
if (obj1[key] !== obj2[key]) diff[key] = obj2[key];
5
6
return diff;
7
}, {});
8
but the output is without surname: "kowalski"
.
Expected output:
JavaScript
1
2
1
{surname: "kowalski", age: 34, city: "Warszawa", friend: "Ala"}
2
Advertisement
Answer
Please use this code
JavaScript
1
11
11
1
const find = Object.entries(objCombined).reduce((diff, [key]) => {
2
if (!obj2[key]) {
3
diff[key] = obj1[key];
4
return diff;
5
}
6
7
if (obj1[key] !== obj2[key]) diff[key] = obj2[key];
8
9
return diff;
10
}, {});
11