Skip to content

Instantly share code, notes, and snippets.

@jonathanws
Last active December 10, 2020 07:14
Show Gist options
  • Save jonathanws/8ce2e1823bfa732ccdde9ad43167c81a to your computer and use it in GitHub Desktop.
Save jonathanws/8ce2e1823bfa732ccdde9ad43167c81a to your computer and use it in GitHub Desktop.
Prompt 3
const input = {
a: {
b: {
c: 12,
d: "Hello World",
},
e: [1, 2, 3],
},
hi: "there",
checks: {
null: null,
boolean: true,
boolean2: false,
function: function () {},
},
};
// Helper function to determine which fields to leave alone
const canGoDeeper = (obj) =>
typeof obj === "object" && !Array.isArray(obj) && obj != null;
// main recursive function
const flatten = (obj, prefix = "", res = {}) => {
return Object.entries(obj).reduce((r, [key, val]) => {
const k = `${prefix}${key}`;
if (canGoDeeper(val)) {
flatten(val, `${k}/`, r);
} else {
res[k] = val;
}
return r;
}, res);
};
console.log(flatten(input));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment