source: https://github.com/burakcan/mb
var mb=p=>o=>p.map(c=>o=(o||{})[c])&&o
// in ES5:
var mb = function(pathArray) {
return function(obj) {
return pathArray.map(function(c) {
return obj = ( obj || {} )[c];
}) && obj;
}
}
var obj1 = {
a: {
b: [{ hello: "world" }]
}
}
Pass an array to the mb
function that represents the path to the deeply nested item you would like to access. In this example we would like to access a.b[0].hello
from obj1
above.
So a.b[0].hello
gets written out in an array like this ["a", "b", 0, "hello"]
var getHello = mb(["a", "b", 0, "hello"]);
This will return a function which you will then execute using the object you would like to get data from as an argument:
getHello(obj1);
internally this is what its doing. Going through each item and resetting the internal object argument in each step
["a", "b", 0, "hello"].map(function(c) {
return obj = ( obj || {} )[c];
});
set obj to obj.a
a: {
b: [{ hello: "world" }]
}
set obj to obj.b
b: [{ hello: "world" }]
set obj to obj[0]
{ hello: "world" }
set obj to obj.hello
"world"
&& obj
to check if obj is still defined, return it if it is
and that's how you get to the value of a.b[0].hello
("world") without throwing any Errors.
This is similar to lodash.get