Compare nested objects in JavaScript and return keys equality

前端 未结 5 968
伪装坚强ぢ
伪装坚强ぢ 2020-12-31 17:31

I have two nested objects obj1 and obj2 and I want to compare them and the recursively return an object that for each nested key has a equality-lik

5条回答
  •  一整个雨季
    2020-12-31 17:53

    A recursive example,

    var obj1 = {
            prop1: 1,
            prop2: "foo",
            prop3: {
                prop4: 2,
                prop5: "bar"
            },
            prop7: {},
        }
    
        var obj2 = {
            prop1: 3,
            prop2: "foo",
            prop3: {
                prop4: 2,
                prop5: "foobar"
            },
            prop6: "new",
            prop7: {},
            prop8: {},
        }
    
        var result = {};
    
        function compare(obj1, obj2, obj_) {
            for (let k in obj1) {
                var type = typeof obj1[k];
                if (type === 'object') {
                    obj_[k] = {};
                    if (!obj2[k]){
                        obj_[k] = false;
                    }else if ((Object.entries(obj1[k]).length === 0 && obj1[k].constructor === Object) && (Object.entries(obj2[k]).length === 0 && obj2[k].constructor === Object)) {
                        obj_[k] = true;
                    } else {
                        compare(obj1[k], obj2[k], obj_[k]);
                    }
                } else {
                    obj_[k] = (obj1[k] === obj2[k]);
                }
    
            }
        }
    
        if (Object.keys(obj1).length < Object.keys(obj2).length) { //check if both objects vary in length.
            var tmp = obj1;
            obj1 = obj2;
            obj2 = tmp;
        }
    
        compare(obj1, obj2, result);
    
        console.log(result);

提交回复
热议问题