I\'m trying to flatten an object where the keys will be the full path to the leaf node. I can recursively identify which are the leaf nodes but stuck trying to construct the
Here is an interative solution using object-scan.
object-scan is a data processing tool, so the main advantage here is that it would be easy to do further processing or processing while extracting the desired information
// const objectScan = require('object-scan');
const myData = { one: 1, two: { three: 3 }, four: { five: 5, six: { seven: 7 }, eight: 8 }, nine: 9 };
const flatten = (data) => {
const entries = objectScan(['**'], {
rtn: 'entry',
joined: true,
filterFn: ({ isLeaf }) => isLeaf
})(data);
// could use Object.fromEntries(entries.reverse()) instead
return entries.reduceRight((p, [k, v]) => {
p[k] = v;
return p;
}, {});
};
console.log(flatten(myData));
// => { one: 1, 'two.three': 3, 'four.five': 5, 'four.six.seven': 7, 'four.eight': 8, nine: 9 }
.as-console-wrapper {max-height: 100% !important; top: 0}
Disclaimer: I'm the author of object-scan