Last active
December 10, 2020 07:14
-
-
Save jonathanws/8ce2e1823bfa732ccdde9ad43167c81a to your computer and use it in GitHub Desktop.
Prompt 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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