Skip to content

Instantly share code, notes, and snippets.

@exbotanical
Last active July 7, 2020 23:56
Show Gist options
  • Save exbotanical/4ed44791dbb65b75796989605986733e to your computer and use it in GitHub Desktop.
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)
// 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