Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Return differences between two Objects?

Can someone show me how to return the new data when comparing something like this. using vanilla JavaScript.

{
    "48": "{\"sid\":\"48\",\"name\":\"title 1\"}",
    "77": "{\"sid\":\"77\",\"name\":\"The blahblah title\"}"
}

compared to this

{
    "48": "{\"sid\":\"48\",\"name\":\"title 1\"}",
    "77": "{\"sid\":\"77\",\"name\":\"The blahblah title\"}",
    "83": "{\"sid\":\"83\",\"name\":\"The blahblah derp\"}",
    "87": "{\"sid\":\"87\",\"name\":\"The derpy title 4\"}"
}

it should return only the differences.

{
    "83": "{\"sid\":\"83\",\"name\":\"The blahblah derp\"}",
    "87": "{\"sid\":\"87\",\"name\":\"The derpy title 4\"}"
}
like image 479
aestheticode Avatar asked Sep 12 '19 04:09

aestheticode


Video Answer


1 Answers

You can use Object.keys() and Array.includes() to do that.

var data = {
  "48": "{\"sid\":\"48\",\"name\":\"title 1\"}",
  "77": "{\"sid\":\"77\",\"name\":\"The blahblah title\"}",
  "83": "{\"sid\":\"83\",\"name\":\"The blahblah derp\"}",
  "87": "{\"sid\":\"87\",\"name\":\"The derpy title 4\"}"
};

var obj1 = {
  "48": "{\"sid\":\"48\",\"name\":\"title 1\"}",
  "77": "{\"sid\":\"77\",\"name\":\"The blahblah title\"}"
};

var result = {};
var keys = Object.keys(obj1);

for (var key in data) {
 if (!keys.includes(key)) {
  result[key] = data[key];
 }
}

console.log(result);
like image 191
Nikhil Avatar answered Nov 15 '22 17:11

Nikhil