Skip to content

Instantly share code, notes, and snippets.

@kieraneglin
kieraneglin / safe-access-object.js
Last active Feb 28, 2019
Safely Access Deeply Nested Objects In JavaScript
View safe-access-object.js
// Problem: how do you access a deeply nested object that you're not certain exists?
// if(object.user && object.user.post && object.user.post[0] && object.user.post[0].comment) {
// return object.user.post[0].comment
// }
// and that's horrifying. Here's something better
const idx = (props, object) => props.reduce((prefix, val) => (prefix && prefix[val]) ? prefix[val] : null, object)
// Usage:
nestedObj = {...}
@mikaelbr
mikaelbr / destructuring.js
Last active Sep 22, 2020
Complete collection of JavaScript destructuring. Runnable demos and slides about the same topic: http://git.mikaelb.net/presentations/bartjs/destructuring
View destructuring.js
// === Arrays
var [a, b] = [1, 2];
console.log(a, b);
//=> 1 2
// Use from functions, only select from pattern
var foo = () => [1, 2, 3];
You can’t perform that action at this time.