UNPKG

885 BJavaScriptView Raw
1// Given objects A (base) and B (test), returns a new object
2// with set difference of B - A;
3// i.e. an object with fields of B that are either not in A
4// or has a difference value from A
5const isEmpty = require('lodash/isEmpty')
6const isObject = require('./is-object')
7
8function objectDiff(A, B) {
9 // if types differ, or are "scalars" (including arrays), ignore it
10 if (!isObject(A) || !isObject(B)) return B
11
12 return Object.keys(B).reduce((result, fieldB) => {
13 if (isObject(B[fieldB])) {
14 const subResult = objectDiff(A[fieldB], B[fieldB])
15 if (!isEmpty(subResult)) result[fieldB] = subResult
16 } else {
17 // it's a "scalar", so compare B's field as-is.
18 // For "object-like" stuff like arrays, it will still be "different".
19 if (A[fieldB] !== B[fieldB]) result[fieldB] = B[fieldB]
20 }
21
22 return result
23 }, {})
24}
25
26module.exports = objectDiff