Skip to content

Instantly share code, notes, and snippets.

@peter
Last active October 5, 2021 08:59
Show Gist options
  • Save peter/56e98400801b9299665e228a235bd85c to your computer and use it in GitHub Desktop.
Save peter/56e98400801b9299665e228a235bd85c to your computer and use it in GitHub Desktop.
Compact/Normalize data (omit null/empty values) for equality checks
const { isEmpty, isEqual } = require('lodash')
function deepPickBy(obj, predicate) {
if (Array.isArray(obj)) {
return obj.map((v) => deepPickBy(v, predicate));
} else if (obj && typeof obj === 'object') {
return Object.keys(obj).reduce((acc, key) => {
const v = obj[key]
if (v && typeof v === 'object' && Object.keys(v).length > 0) {
acc[key] = deepPickBy(v, predicate);
} else if (predicate(v)) {
acc[key] = v;
}
return acc
}, {});
}
}
const data1 = {
foo: 1,
bar: null,
baz: [],
bla: {
nested: false,
nestedNull: null,
nestedEmpty: {},
}
}
const data2 = {
foo: 1,
bla: {
nested: false,
}
}
const normalize = (obj) => deepPickBy(obj, (v) => v != null && (typeof v !== 'object' || !isEmpty(v)))
console.log('isEqual(data1, data2)', isEqual(data1, data2))
console.log('data1', JSON.stringify(data1, null, 4))
console.log('data2', JSON.stringify(data2, null, 4))
console.log('normalize(data1)', JSON.stringify(normalize(data1), null, 4))
console.log('normalize(data2)', JSON.stringify(normalize(data2), null, 4))
console.log('isEqual(normalize(data1), normalize(data2))', isEqual(normalize(data1), normalize(data2)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment