Created
December 10, 2021 07:05
-
-
Save alejandrolechuga/03a1e8283b0cc3f921ce0c27445e4422 to your computer and use it in GitHub Desktop.
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
// 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