From f26e746c2b55815e7dc8d4f0ccdb6660fff390f8 Mon Sep 17 00:00:00 2001 From: "D. Berge" Date: Mon, 23 Oct 2023 18:58:37 +0200 Subject: [PATCH] Add flatEntries utility --- lib/www/server/lib/utils/flatEntries.js | 28 +++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 lib/www/server/lib/utils/flatEntries.js diff --git a/lib/www/server/lib/utils/flatEntries.js b/lib/www/server/lib/utils/flatEntries.js new file mode 100644 index 0000000..a80df6b --- /dev/null +++ b/lib/www/server/lib/utils/flatEntries.js @@ -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 +};