object diff javascript

Solutions on MaxInterview for object diff javascript by the best coders in the world

showing results for - "object diff javascript"
Jayson
29 Jan 2016
1// const { inspect } = require('util')
2const { transform, isEqual, isArray, isObject } = require('lodash')
3
4/**
5 * Find difference between two objects
6 * https://davidwells.io/snippets/get-difference-between-two-objects-javascript
7 *
8 * @param  {object} origObj - Source object to compare newObj against
9 * @param  {object} newObj  - New object with potential changes
10 * @return {object} differences
11 */
12function difference(origObj, newObj) {
13  function changes(newObj, origObj) {
14    let arrayIndexCounter = 0
15    return transform(newObj, function (result, value, key) {
16      if (!isEqual(value, origObj[key])) {
17        let resultKey = isArray(origObj) ? arrayIndexCounter++ : key
18        result[resultKey] =
19          isObject(value) && isObject(origObj[key])
20            ? changes(value, origObj[key])
21            : value
22      }
23    })
24  }
25  return changes(newObj, origObj)
26}
27
28/* Usage */
29
30const originalObject = {
31  foo: 'bar',
32  baz: 'fizz',
33  cool: true,
34  what: {
35    one: 'one',
36    two: 'two'
37  },
38  wow: {
39    deep: {
40      key: ['a', 'b', 'c'],
41      values: '123'
42    }
43  },
44  array: ['lol', 'hi', 'there']
45}
46
47const newObject = {
48  foo: 'bar',
49  baz: 'fizz',
50  cool: false, // <-- diff
51  what: {
52    one: 'one',
53    two: 'twox' // <-- diff
54  },
55  wow: {
56    deep: {
57      key: ['x', 'y', 'c'], // <-- diff
58      values: '098' // <-- diff
59    }
60  },
61  array: ['lol', 'hi', 'difference'] // <-- diff
62}
63
64// Get the Diff!
65const diff = difference(originalObject, newObject)
66
67console.log(inspect(diff, {showHidden: false, depth: null, colors: true}))
68
69// result:
70// {
71//   cool: false,
72//   what: { two: 'twox' },
73//   wow: { deep: { key: [ 'x', 'y' ], values: '098' } },
74//   array: [ 'difference' ]
75// }
76
77
78if (diff.cool) {
79  console.log('Coolness changed to', diff.cool)
80}
81
82