Skip to content

Instantly share code, notes, and snippets.

@alejandrolechuga
Created December 10, 2021 07:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alejandrolechuga/03a1e8283b0cc3f921ce0c27445e4422 to your computer and use it in GitHub Desktop.
Save alejandrolechuga/03a1e8283b0cc3f921ce0c27445e4422 to your computer and use it in GitHub Desktop.
// DeepGet
let resp = {
collection: [
{
name: 'batman',
metadata: {
rating: 'PG-14',
year: 1985
}
},
{
name: 'joker',
metadata: {
rating: 'PG-14',
year: 2019
}
},
{
name: 'toy story',
metadata: {
rating: 'PG-14',
year: 2000
}
}
]
};
function deepGet(obj, path) {
path = Array.isArray(path) ? path : [path];
let ref = obj;
for (let key of path) {
if (key in ref) {
ref = ref[key];
} else {
return undefined;
}
}
return ref;
}
console.log(deepGet(resp, 'collection'));
console.log(deepGet(resp, ['collection', 2, 'metadata', 'year']));
// console.log(resp.collection[0].metadata.year);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment