0

I want to show the difference between a components current and next props. For example:

componentWillReceiveProps(nextProps) {
    let diff = someFunction(this.props, nextProps);
    console.log(diff);
} 

How is this done?

JoeTidee
  • 24,754
  • 25
  • 104
  • 149
  • Would answers to something like this help? I don't think there's something native to React for this: http://stackoverflow.com/questions/264430/how-can-i-get-a-list-of-the-differences-between-two-javascript-object-graphs – Ben Hare Nov 11 '16 at 00:49

2 Answers2

1

This npm package seemed to work nicely:

https://github.com/Tixit/odiff

JoeTidee
  • 24,754
  • 25
  • 104
  • 149
0

You can do a shallow comparison with a function like the following (I'm using ES6):

function compareObjects (objectA, objectB) {
    if (objectA === objectB) {
        return true // return true if both variables are referencing the same object
    }

    let key

    // check what property does objectA have that objectB has not
    for (key in objectA) {
         if (objectA.hasOwnProperty(key) && !objectB.hasOwnProperty(key)) {
              return false // return false if there's a difference
         }
    }

    // check what property does objectB have that objectA has not
    for (key in objectB) {
         if (objectB.hasOwnProperty(key) && !objectA.hasOwnProperty(key)) {
              return false // return false if there's a difference
         }
    }
}

Note that this is only shallow checking and does the comparison on first level. It only compares if the objects given consist of the same values (therefore it's called shallow).

Leo Napoleon
  • 969
  • 6
  • 11
  • Thanks for the answer, though I was looking for something that would analyse deeper levels of the objects. – JoeTidee Nov 11 '16 at 01:05
  • @JoeTidee This answer does exactly what you need http://stackoverflow.com/a/1144249/5444014 – Leo Napoleon Nov 11 '16 at 01:13
  • Those functions simply compare to see if two objects are identical, they do not present the differences. – JoeTidee Nov 11 '16 at 01:19
  • You can easily create an empty Array in the beginning of the function and push every difference you find into it instead of return false. Then in the end of the function, return the filled array. – Leo Napoleon Nov 11 '16 at 01:21