Last active
July 7, 2020 23:56
-
-
Save exbotanical/4ed44791dbb65b75796989605986733e to your computer and use it in GitHub Desktop.
How to Find Props on a Nested Object (without needing to know what the Object looks like)
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
// Code snippets from an article I wrote on working with JavaScript Objects | |
// canonical link: https://goldmund.sh/entries/work-with-javascript-objects-like-a-pro | |
// medium: https://medium.com/@exbotanical/work-with-javascript-objects-like-a-pro-876437a6a668 | |
/* How to Find Props on a Nested Object (without needing to know what the Object looks like) */ | |
const nestedPerson = { | |
metadata: { | |
id: 123456789, | |
claims: { | |
tokens: { | |
current: "cnVwYXVsaXN0aGVncmVhdGVzdAo=" | |
} | |
} | |
}, | |
instanceData: { | |
personal: { | |
name: "RuPaul", | |
surname: "Charles", | |
}, | |
vocational: { | |
profession: "being awesome", | |
skills: { | |
charisma: true, | |
uniqueness: true, | |
nerve: true, | |
talent: true | |
} | |
} | |
} | |
}; | |
const walkRefined = (targetObject, ...args) => { | |
return args.reduce((targetObject, root) => { | |
return targetObject && targetObject[root]; | |
}, targetObject); | |
}; | |
const propFound = walkRefined(nestedPerson,"instanceData", "vocational", "profession" ); | |
console.log(propFound); | |
// being awesome | |
const isNested = x => Object(x) === x && !Array.isArray(x); | |
const formatter = (...args) => args.join("."); | |
const collateKeys = (obj, store=[], accumulator=[]) => | |
Object.keys(obj).reduce((accumulator, prop) => | |
isNested(obj[prop]) | |
? [...accumulator, ...collateKeys(obj[prop], [...store, prop], accumulator)] | |
: [...accumulator, formatter(...store, prop)] | |
, []); | |
const keysList = collateKeys(nestedPerson); | |
console.log(keysList); | |
/* | |
[ | |
'metadata.id', | |
'metadata.claims.tokens.current', | |
'instanceData.personal.name', | |
'instanceData.personal.surname', | |
'instanceData.vocational.profession', | |
'instanceData.vocational.skills.charisma', | |
'instanceData.vocational.skills.uniqueness', | |
'instanceData.vocational.skills.nerve', | |
'instanceData.vocational.skills.talent' | |
] | |
*/ | |
console.log(keysList.filter(x => x.endsWith("profession"))); | |
// [ 'instanceData.vocational.profession' ] | |
// aka the precise location of our prop |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment