red
red

Reputation: 305

JavaScript (Lodash) - Deep comparison of two objects

Let's say I have two deep objects:

var oldData = {
  "id": 1,
  "first_name": "Eric",
  "last_name": "Henry",
  "info": {
    "email": "[email protected]",
    "gender": "Male",
    "ip_address": "7.11.169.150",
    "age": 11
  }
};

var newData = {
  "id": 2,
  "first_name": "Tommy",
  "last_name": "Henry",
  "info": {
    "email": "[email protected]",
    "gender": "Male",
    "ip_address": "7.11.169.150",
    "age": 15
  }
};

How would I use lodash (or JavaScript) to traverse through each object and get the value of each different value, so in the top case it would be

[
   {old: 1, new: 2},
   {old: 'Eric', new: 'Tommy'},
   {old: '[email protected]', new: '[email protected]'},
   {old: 11, new: 15},
]

Here is what I have so far:

var oldData = {
  "id": 1,
  "first_name": "Eric",
  "last_name": "Henry",
  "info": {
    "email": "[email protected]",
    "gender": "Male",
    "ip_address": "7.11.169.150",
    "age": 11
  }
};

var newData = {
  "id": 2,
  "first_name": "Tommy",
  "last_name": "Henry",
  "info": {
    "email": "[email protected]",
    "gender": "Male",
    "ip_address": "7.11.169.150",
    "age": 15
  }
};

var diffObj = _.difference(_.keys(oldData), _.keys(newData));

console.log(JSON.stringify(diffObj, null, 4));
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

Upvotes: 5

Views: 9781

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The solution using custom recursive function compareUserData and Object.keys() function:

var oldData = { "id": 1, "first_name": "Eric", "last_name": "Henry", "info": { "email": "[email protected]", "gender": "Male", "ip_address": "7.11.169.150", "age": 11 }
}; 
var newData = { "id": 2, "first_name": "Tommy", "last_name": "Henry", "info": { "email": "[email protected]", "gender": "Male", "ip_address": "7.11.169.150", "age": 15 }
};

function compareUserData(oldData, newData, result) {
    Object.keys(oldData).forEach(function (k) {
        if (typeof oldData[k] !== 'object') {
            if (oldData[k] != newData[k]) this.push({'old': oldData[k], 'new': newData[k]});
        } else {
            compareUserData(oldData[k], newData[k], this);
        }
    }, result);

    return result;
}

var result = compareUserData(oldData, newData, []);
console.log(result);

Upvotes: 3

PaulDennetiere
PaulDennetiere

Reputation: 179

You may want to iterate through your objects properties, and check manually if something changed. To see how you can iterate on properties : Iterate through object properties

EDIT : Your object has nested properties, read this post to see how you can check that too : How do I check if an object has a property in JavaScript?

Upvotes: 0

Related Questions