-2

I am trying to compare the object by only KEYS.

var obj1 = [ {"depid": "100", "depname": ""}, {"city": "abc", "state": "xyz"}, {"firstName": "John", "lastName": "Doe", "contactno": {"ph": 12345, "mob": 485428428}} ];
var obj2 = [ {"firstName": "John", "lastName": "Doe", "contactno": {"ph": 12345, "mob": 485428428}}, {"depid": "100", "depname": "role"}, {"city": "abc", "state": "xyz"} ];

For example, If we compare object in obj1 {"depid": "100", "depname": ""} with obj2 {"depid": "100", "depname": "role"}, must return true. Since the keys are same. I need to set the values of obj2 in obj1.

//Expected result
obj1 = [ {"depid": "100", "depname": "role"}, {"city": "abc", "state": "xyz"}, {"firstName": "John", "lastName": "Doe", "contactno": {"ph": 12345, "mob": 485428428}} ]

I have tried the solution provided in this link But still not able to compare only on object keys and update the values from obj2 to obj1

Community
  • 1
  • 1
user4324324
  • 559
  • 3
  • 7
  • 25

1 Answers1

0

This function checks: for each object in obj1, it will look for each key in obj2. So it is checking if deptid is present in obj2, if it is then return true. If

var f = function(obj1, obj2){
    console.log('Starting...', obj1.length);
    for(var i in obj1){
        var memberObj1 = obj1[i];
        var memberObj1Keys = Object.keys(memberObj1);
        console.log('Keys in each object', memberObj1Keys);
        // console.log('Checking for ', memberObj1);
        for(var j in obj2){
            var memberObj2 = obj2[j];
            console.log('Object2 ', memberObj2);
            for(var eachKey in memberObj1Keys){
                console.log('Looking for %s in obj2', memberObj1Keys[eachKey]);
                if(memberObj2[memberObj1Keys[eachKey]]){
                    console.log('Found');
                    return true;
                }
            }
        }
        console.log('======================');
    }
 return false;
}

using the function.

var result = f(obj1, obj2);
console.log(result);

This is quick implementation for your problem. I have not tried to optimize the loop till now.

Any edit is welcome.

Gaurav Gupta
  • 4,586
  • 4
  • 39
  • 72