Skip to content

Instantly share code, notes, and snippets.

@matiaslopezd
Last active December 1, 2020 19:05
Show Gist options
  • Save matiaslopezd/7e51f8573a997d2c67f299a71270c37c to your computer and use it in GitHub Desktop.
Save matiaslopezd/7e51f8573a997d2c67f299a71270c37c to your computer and use it in GitHub Desktop.
Convert JSON to array with dot notation
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;
}
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