Sunday 28 February 2016

javascript - How to compare two objects with nested array of object using loop





I have two objects, suppose



A = {
name:'abc',
age: 20,
areaOfInterest:[
{ inSports:'badminton', outSports:'football' },
{ inSports:'chess', outSports:'tennis' }]
}


B = {
age: 20,
name: 'abc',
areaOfInterest:[
{ inSports:'chess', outSports:'tennis' },
{ inSports:'badminton', outSports:'football' }]
}


As in given example above, the sequence of keys is different in both objects. Also, while comparing I dont want to go with




if(A.name == B.name)
if(A.areOfInterest.inSports == B.areOfInterest.inSports)


I want to compare them using loop like for...In or for...Of



Here is what I tried,






A = {
name:'abc',
age: 20,
areaOfInterest:[
{ inSports:'badminton', outSports:'football' },
{ inSports:'chess', outSports:'tennis' }
]
}


B = {
age:20,
name: 'abc',
areaOfInterest:[
{ inSports:'chess', outSports:'tennis' },
{ inSports:'badminton', outSports:'football' }
]
}

function objCompare(obj1, obj2){

for (var [key, value] of Object.entries(obj1)) {
for (var [k, v] of Object.entries(obj2)){
if(k == key && v == value)
console.log(true)
}
}
}

console.log(objCompare(A,B));






I am not getting true result. It gives undefined when it compares A.areOfInterest with B.areOfInterest


Answer



I'd do something like this:





A = {

name:'abc',
age: 20,
areaOfInterest:[
{ inSports:'badminton', outSports:'football' },
{ inSports:'chess', outSports:'tennis' }
]
}

B = {
age:'abc',

name: 20,
areaOfInterest:[
{ inSports:'chess', outSports:'tennis' },
{ inSports:'badminton', outSports:'football' }
]
}

C = {
age:'abc',
name: 20,

areaOfInterest:[
{ inSports:'chess', outSports:'tennis' },
{ inSports:'badminton', outSports:'football' }
]
}

function objCompare(obj1, obj2){
var same = true;
for (var [key, value] of Object.entries(obj1)) {
if(typeof value === 'object') {

same = objCompare(obj1[key], obj2[key]);
} else {
if(obj1[key] != obj2[key]) same = false;
}
}

return same;
}

console.log(objCompare(A,B));

console.log(objCompare(B,C));





So using the function recursively you can iterate over other objects inside the main objects.



Hope that helps you :)


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...