-1

want to compare 2 out and miss out missing field and change in value recursively

obj1 = {
  "val1": "test",
  "stream": {
    "key": true,
    "value": false
  },
  "val2": "test",
  "val3": "test",
}

obj2 = {
  "val1": "test",
  "stream": {
    "key": false,
    "value": false
  }
}

I need 2 outputs as below

output1 = {
  "val2": "test",
  "val3": "test"
}

output2 = {
  "stream": {
    "key": true
  }
}
ThS
  • 4,597
  • 2
  • 15
  • 27
Gautham Shetty
  • 361
  • 1
  • 5
  • 13

1 Answers1

1

It is some version of deep comparing objects. I combined both outputs into one function since they both represent a different attribute.

var obj1 = {
  "val1": "test",
  "stream": {
    "key": true,
    "value": false
  },
  "val2": "test",
  "val3": "test",
}

var obj2 = {
  "val1": "test",
  "stream": {
    "key": false,
    "value": false
  }
}


function diffCompare(obj1, obj2) {

  var list = [];

  function is_obj(obj) {
    return typeof obj === 'object' && obj !== null
  }

  function iterate(obj1, obj2, path) {
    path = path || []
    Object.keys(obj1).forEach(function(key) {

      if (obj1[key] != obj2[key]) {
        if (is_obj(obj1[key]) && is_obj(obj2[key])) {
          iterate(obj1[key], obj2[key], path.concat(key))
        } else {
          list.push({
            path: path.concat(key),
            value: obj1[key]
          })
        }
      }

    })
  }
  iterate(obj1, obj2)
  // console.log(list)

  // building result object:
  var result = list.reduce(function(agg, {path, value}) {
    var pointer = agg;
    while (path.length) {
      var part = path.shift();
      pointer[part] = pointer[part] || {}
      if (path.length) {
        pointer = pointer[part]
      } else {
        pointer[part] = value;
      }
    }
    return agg;
  }, {});
  
  return result;
}

console.log(diffCompare(obj1, obj2))
.as-console-wrapper {
  max-height: 100% !important
}
IT goldman
  • 14,885
  • 2
  • 14
  • 28