1 min readDec 21, 2023
The implemented code does entirely skip null-values (thus, any path to a null-values gets omitted) and does not handle array-values properly (thus arrays are not getting "squashed"). But a squashObject function should cover such valid data-values as well.
A just slightly updated version of the code already does the trick …
function squashIt(source, path = '') {
const squashed = {};
for (let key in source) {
const keypath = path ? `${ path }.${ key }` : key;
const value = source[key];
if (!!value && typeof value === 'object') {
Object.assign(squashed, squashObject(value, keypath));
} else {
squashed[keypath] = value;
}
}
return squashed;
}
… and enables the “squashing” of valid JSON-compatible data-structures …
const sampleData = {
a: 1,
b: {
c: 2,
d: {
e: ['foo', {
a: ['bar', 'baz', 'biz'],
b: {
c: null,
d: 4,
},
}, 'buzz'],
f: {
g: null,
h: 4,
},
},
},
i: 5,
};
const squashed = squashIt(sampleData);
console.log({ squashed });
… even though it still is not bulletproof.