Awesome
<div align="center"> <h1>mb</h1> <img height="80" width="80" alt="goat" src="https://d1j8pt39hxlh3d.cloudfront.net/development/emojione/4.0/833/14168.svg?1533081835" />Exception-free nested nullable attribute accessor. An alternative to facebookincubator/idx in 38 bytes.
</div/> <hr />Install
Just copy/paste this function into your project:
var mb=p=>o=>p.map(c=>o=(o||{})[c])&&o
Alternatively, you can download mb.js.
Use
var getHello = mb(["a", "b", 0, "hello"]);
var getHelloLength = mb(["a", "b", 0, "hello", "length"]);
var obj1 = {
a: {
b: [{ hello: "world" }]
}
};
var obj2 = {
c: {
d: "e"
}
};
getHello(obj1); // world
getHelloLength(obj1); // 5
getHello(obj2); // undefined
getHelloLength(obj2); // undefined
Contribution and Code-Golfing
- Clone and shorten current code.
- Please open
test.html
in your browser and open console to see if all the tests pass.