Last active
December 1, 2020 19:05
-
-
Save matiaslopezd/7e51f8573a997d2c67f299a71270c37c to your computer and use it in GitHub Desktop.
Convert JSON to array with dot notation
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
function toDots(object, array = []) { | |
const deepValue = (obj, path) => path.replace(/\[|\]\.?/g, '.').split('.').filter(s => s).reduce((acc, val) => acc && acc[val], obj); | |
function parseToDots(obj, key) { | |
const value = deepValue(obj, key); | |
array.push(key); // Add if you want add only certains fields | |
if (typeof value === 'object') Object.keys(value).forEach(key2 => parseToDots(obj, `${key}.${key2}`)); | |
} | |
Object.keys(object).forEach(key => parseToDots(object, key)); | |
return array; | |
} |
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
function toDots(t,e=[]){const c=(t,e)=>e.replace(/\[|\]\.?/g,".").split(".").filter(t=>t).reduce((t,e)=>t&&t[e],t);return Object.keys(t).forEach(o=>(function t(o,n){const r=c(o,n);e.push(n),"object"==typeof r&&Object.keys(r).forEach(e=>t(o,`${n}.${e}`))})(t,o)),e} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment