For example I wanted to compare below 2 JSON and get the return value with common JSON key value pair.
JSON1 = [{
"info" : {
"name": "xyz"
},
"add" : "london",
"no" : 1234,
"gender" : "male"
}]
Another JSON is :
JSON2 = [{
"info" : {
"name": "abc"
},
"add" : "london",
"no" : 2456
}]
Need return value as JSON like below with common values but difference should be empty.
json3 = [{
"info" : {
"name": ""
},
add : "london",
no : "",
gender : male
}]
You could create a combineObjects() function that combines input objects recursively.
We'll enumerate the input objects keys, then return an empty value for each property if the values are not the same for the two inputs.
If the values are the same or are missing in either object, we'll return the value of the obj1 or obj2 property.
const json1 = [{ "info" : { "name": "xyz" }, "add" : "london", "no" : 1234, "gender" : "male" }];
const json2 = [{ "info" : { "name": "abc"}, "add" : "london", "no" : 2456 }];
function combineObjects(obj1, obj2) {
const result = {};
// Get all keys...
let keys = [...new Set([...Object.keys(obj1), ...Object.keys(obj2)])];
for(let k of keys) {
if (obj1[k] && obj2[k] && typeof(obj1[k]) === 'object') {
result[k] = combineObjects(obj1[k], obj2[k]);
} else if (obj1[k] === obj2[k]) {
result[k] = obj1[k];
} else {
result[k] = (obj1[k] && obj2[k]) ? '' : obj1[k] || obj2[k];
}
}
return result;
}
const result = combineObjects(json1, json2);
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.1/luxon.min.js" integrity="sha512-Nw0Abk+Ywwk5FzYTxtB70/xJRiCI0S2ORbXI3VBlFpKJ44LM6cW2WxIIolyKEOxOuMI90GIfXdlZRJepu7cczA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>