Something like this should work. A recursive function that just runs through all the keys of the object.
It doesn't handle arrays, but it can be modified to if that's a requirement.
function findCommonValues(obj1, obj2) {
var result = {}
for (let key in obj1) {
if (obj1[key] && obj1[key] === obj2[key]) result[key] = obj1[key]
else if (typeof obj1[key] === 'object' && obj1[key] !== null) {
result[key] = findCommonValues(obj1[key], obj2[key])
}
}
return result;
}
const obj1 = {
"val1": "test",
"stream": {
"iscommisonAccount": false,
"istradeAccount": true
}
}
const obj2 = {
"val1": "test",
"stream": {
"iscommisonAccount": true,
"istradeAccount": true
}
}
const obj3 = {
"val1": "test",
"stream": {
"iscommisonAccount": false,
"istradeAccount": true
}
}
const obj4 = {
"val1": "test",
"stream": {
"iscommisonAccount": true,
"istradeAccount": false
}
}
const obj5 = {
"val1":"test",
"stream":{
"iscommisonAccount":true,
"istradeAccount":true
}
}
const obj6 = {
"val1":"test",
"stream":{
"iscommisonAccount":true,
"istradeAccount":true
}
}
console.log(findCommonValues(obj1, obj2))
console.log(findCommonValues(obj3, obj4))
console.log(findCommonValues(obj5, obj6))
If you want it as small as possible. This is really the best I can do.
const commonValues = (obj1, obj2) => Object.keys(obj1).reduce((result, key) => obj1[key] && obj1[key] === obj2[key] ? { ...result, [key]: obj1[key] } : typeof obj1[key] === 'object' && obj1[key] !== null ? { ...result, [key]: commonValues(obj1[key], obj2[key]) } : result, {});
const obj1 = {
"val1": "test",
"stream": {
"iscommisonAccount": false,
"istradeAccount": true
}
}
const obj2 = {
"val1": "test",
"stream": {
"iscommisonAccount": true,
"istradeAccount": true
}
}
const obj3 = {
"val1": "test",
"stream": {
"iscommisonAccount": false,
"istradeAccount": true
}
}
const obj4 = {
"val1": "test",
"stream": {
"iscommisonAccount": true,
"istradeAccount": false
}
}
const obj5 = {
"val1": "test",
"stream": {
"iscommisonAccount": true,
"istradeAccount": true
}
}
const obj6 = {
"val1": "test",
"stream": {
"iscommisonAccount": true,
"istradeAccount": true
}
}
console.log(commonValues(obj1, obj2))
console.log(commonValues(obj3, obj4))
console.log(commonValues(obj5, obj6))
TypeScript Version
export type KeyValueObject = {
[key: string]: number | boolean | string | KeyValueObject
}
export const isKeyValueObject = (obj1: number | boolean | string | KeyValueObject): obj1 is KeyValueObject => typeof obj1 === 'object' && obj1 !== null;
export const commonValues = (obj1: KeyValueObject, obj2: KeyValueObject): KeyValueObject =>
Object.keys(obj1).reduce((result, key) =>
obj1[key] && obj1[key] === obj2[key]
? { ...result, [key]: obj1[key] }
: isKeyValueObject(obj1[key]) && isKeyValueObject(obj2[key])
? { ...result, [key]: commonValues(obj1[key] as KeyValueObject, obj2[key] as KeyValueObject) }
: result,
{}
);