Skip to content

Instantly share code, notes, and snippets.

@benjamw
Last active March 21, 2017 05:09
Show Gist options
  • Save benjamw/67f5ebe0b9f6bf6ef50f642e781d7059 to your computer and use it in GitHub Desktop.
Save benjamw/67f5ebe0b9f6bf6ef50f642e781d7059 to your computer and use it in GitHub Desktop.
JavaScript safe access of deeply nested objects
// https://medium.com/javascript-inside/safely-accessing-deeply-nested-values-in-javascript-99bf72a0855a#.wc89qfbqv
// get returns the element given by path p from object o, returning default d if not found
var get = function(p, o, d) {
return p.reduce( function(xs, x) {
return (xs && xs[x]) ? xs[x] : d;
}, o);
};
// usage:
var props = {
user: {
posts: [
{ title: 'Foo', comments: [ 'Good one!', 'Interesting...' ] },
{ title: 'Bar', comments: [ 'Ok' ] },
{ title: 'Baz', comments: [] },
]
}
}
var comments = get(["user", "posts", 0, "comments"], props); // returns [ 'Good one!', 'Interesting...' ]
var empty = get(["user", "posts", 2, "comments"], props); // returns []
var def1 = get(["user", "posts", 2, "comments", 0], props); // returns undefined
var def2 = get(["user", "posts", 2, "comments", 0], props, "default"); // returns "default"
// alternate syntax
const get = (p, o, d) => p.reduce((xs, x) => (xs && xs[x]) ? xs[x] : d, o)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment