Compare nested objects in JavaScript and return keys equality

前端 未结 5 992
伪装坚强ぢ
伪装坚强ぢ 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 18:13

    You could create a merged object which will have keys of both object. Loop through this object and compare the values for both obj1 and obj2 for each key. If the property is an object, recursively compare the properties. This will work for any level of nesting. Since the properties could be missing from either of the objects, default parameter = {} is added.

    const obj1={prop1:1,prop2:"foo",prop3:{prop4:2,prop5:"bar"},prop7:{pro8:"only in 1"}},
          obj2={prop1:3,prop2:"foo",prop3:{prop4:2,prop5:"foobar"}, prop6: "only in 2"};
        
    const isObject = val => typeof val === 'object' && val // required for "null" comparison
    
    function compare(obj1 = {}, obj2 = {}) {
      const output = {},
            merged = { ...obj1, ...obj2 }; // has properties of both
    
      for (const key in merged) {
        const value1 = obj1[key],
              value2 = obj2[key];
    
        if (isObject(value1) || isObject(value2))
          output[key] = compare(value1, value2) // recursively call
        else
          output[key] = value1 === value2
      }
      
      return output;
    }
    
    console.log(compare(obj1, obj2))

提交回复
热议问题