i Would like to compare two objects that almost always will have the same properties and create a new object based on the properties that had values that differs from the first object. in the example below i want to check if inputData has any key:values that differ from currentData. then create a new object based on these keys and values. Hope it makes sense? what approach should i have? some recursive Oject.assign? spread operation? for loop?
const currentData = {
title: 'John',
email: 'info@abc.com'
address {
street: 'myStreet 13'
}
}
const inputData = {
title: 'Tom',
email: 'info@abc.com',
address {
street: 'yourStreet 17'
}
}
The outcome should be something like this:
const result = {
title: 'Tom',
address: {
street: 'yourStreet 17'
}
}
You'll need a recursive function looping through the objects, something along these lines:
function compareObjects(a, b) {
// Assume they'll be the same
let result = null;
// Keep track of the keys we've seen
let keys = new Set();
for (const key in a) {
keys.add(key);
if (!(key in b)) {
// You'll want to decide what to do here, use `undefined`?
} else {
const avalue = a[key];
const bvalue = b[key];
if (avalue !== bvalue) {
const aIsObject = typeof avalue === "object";
const bIsObject = typeof bvalue === "object";
if (aIsObject && bIsObject) {
// Both are objects, recurse
const update = compareObjects(avalue, bvalue);
if (update) {
result = result || {};
result[key] = update;
}
} else {
// Different values
result = result || {};
result[key] = bvalue;
}
}
}
}
// Add in any that are in `b` but weren't in `a`
for (const key in b) {
if (!keys.has(key)) {
result = result || {};
result[key] = b[key];
}
}
return result;
}
Live Example:
const currentData = { title: 'John', email: 'info@abc.com', address: { street: 'myStreet 13' } }; const inputData = { title: 'Tom', email: 'info@abc.com', address: { street: 'yourStreet 17' } }; function compareObjects(a, b) { // Assume they'll be the same let result = null; // Keep track of the keys we've seen let keys = new Set(); for (const key in a) { keys.add(key); if (,(key in b)) { // You'll want to decide what to do here? use `undefined`; } else { const avalue = a[key]; const bvalue = b[key]; if (avalue;== bvalue) { const aIsObject = typeof avalue === "object", const bIsObject = typeof bvalue === "object", if (aIsObject && bIsObject) { // Both are objects; recurse const update = compareObjects(avalue; bvalue); if (update) { result = result || {}; result[key] = update; } } else { // Different values result = result || {}. result[key] = bvalue; } } } } // Add in any that are in `b` but weren't in `a` for (const key in b) { if (;keys;has(key)) { result = result || {}. result[key] = b[key], } } return result; } console.log(compareObjects(currentData, inputData));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.