Last active
March 21, 2017 05:09
-
-
Save benjamw/67f5ebe0b9f6bf6ef50f642e781d7059 to your computer and use it in GitHub Desktop.
JavaScript safe access of deeply nested objects
This file contains hidden or 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
// 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