mirror of
https://gitlab.com/wgp/dougal/software.git
synced 2025-12-06 10:37:07 +00:00
Add flatEntries utility
This commit is contained in:
28
lib/www/server/lib/utils/flatEntries.js
Normal file
28
lib/www/server/lib/utils/flatEntries.js
Normal 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
|
||||
};
|
||||
Reference in New Issue
Block a user