Skip to content

Instantly share code, notes, and snippets.

@FranciscoG
Last active March 20, 2021 12:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FranciscoG/18f000abd514d63835976c1df3d7e0c4 to your computer and use it in GitHub Desktop.
Save FranciscoG/18f000abd514d63835976c1df3d7e0c4 to your computer and use it in GitHub Desktop.

mb explanation

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;
  }
}

from example 1

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];
});

index 0

set obj to obj.a

  a: {
    b: [{ hello: "world" }]
  }

index 1

set obj to obj.b

  b: [{ hello: "world" }]

index 2

set obj to obj[0]

  { hello: "world" }

index 3

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment