Created
July 27, 2021 08:43
-
-
Save alejandromav/f0750b9d2c25f5b0119e92793e2a9f93 to your computer and use it in GitHub Desktop.
Get JavaScript object nested attributes
This file contains 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 propertiesToArray(obj) { | |
const isObject = val => typeof val === 'object' && !Array.isArray(val); | |
const isArray = val => Array.isArray(val); | |
// Format output keys | |
const addDelimiter = (a, b, type) => a ? `${a}.[${b}: ${type}]` : `[${b}: ${type}]`; | |
const paths = (obj = {}, head = '') => { | |
return Object.entries(obj).reduce((product, [key, value]) => { | |
let fullPath = addDelimiter(head, key, typeof value); | |
// If attribute is an array, get attributes of first item. | |
// This is not exactly true, but an assumption | |
// Remove the if in case you don't want to introspect arrays. | |
if (isArray(value)) { | |
return product.concat(paths(value[0], fullPath)); | |
} | |
return isObject(value) | |
? product.concat(paths(value, fullPath)) | |
: product.concat(fullPath); | |
}, []); | |
} | |
return paths(obj); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment