Add flatEntries utility

This commit is contained in:
D. Berge
2023-10-23 18:58:37 +02:00
parent 39eaf17121
commit f26e746c2b

View File

@@ -0,0 +1,28 @@
/** Converts an object into a list of [ key, value ]
* pairs, like Object.entries(), except that it recurses
* into the object.
*
* Nested keys are joined with `sep` (a `.` by default).
*/
function* flatEntries (obj, sep=".", parents=[]) {
if (typeof obj == "object" && obj !== null) {
for (let key in obj) {
const val = obj[key];
yield* flatEntries(val, sep, [...parents, key]);
}
} else {
yield [[...parents].join(sep), obj];
}
}
/** Run the flatEntries() generator
*/
function entries (obj, sep) {
return [...flatEntries(obj, sep)];
}
module.exports = {
flatEntries,
entries
};