Search code examples
javascriptobjectecmascript-6

How to return an object that is the result of overwritten object elements


How to return an object that is the result of overwritten object elements

I want to return only those elements that firstObject has overwritten in secondObject using Ecmascript6

var firstObject = {
  one: 1,
  four: 55,
  six: 6
}

var secondObject = {
  one: 1,
  two: 2,
  three: 3,
  four: 4
}

returnObject = { four:55 }

Solution

  • If you want to check what properties are present on both objects and difference in values, you can use Object.entries to convert the first object to array. Use reduce to loop thru the array, check and construct the new object.

    var firstObject = {
      one: 1,
      four: 55,
      six: 6
    }
    
    var secondObject = {
      one: 1,
      two: 2,
      three: 3,
      four: 4
    }
    
    var returnObject = Object.entries(firstObject).reduce((c, [k, v]) => {
      if (secondObject[k] !== undefined && v !== secondObject[k]) c[k] = v;
      return c;
    }, {});
    
    console.log(returnObject);


    One liner code:

    var returnObject = Object.entries(firstObject).reduce((c, [k, v]) => secondObject[k] !== undefined && v !== secondObject[k] ? Object.assign(c, {[k]: v}) : c, {})