Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
 
Object.defineProperty(Object.prototype, 'safeGet', { 
  enumerable: false,
  writable: false,
  value: function(p) {
    if (!p) throw new Error('[safeGet] empty value!');
    return p.split('.').reduce((acc, k) => {
      if (acc && k in acc) return acc[k];
      return undefined;
    }, this);
  }
});
// Object to test on
let test = { 
  a: { 
    b: 'b property value',
    c: { }
  } 
}
console.log(`Note that 'Object.safeGet' is not enumerable and will not break existing loops:`)
for(prop in test)
  console.log(`Found prop: ${prop}`);
console.log(`Test known property access: ${test.safeGet('a')}`);
console.log(`Test known sub property access: ${test.safeGet('a.b')}`);
console.log(`Test unknown sub property access: ${test.safeGet('a.c.d.e')}`);
console.log('---------------------------------------------------');
console.log(`Passing an empty value will throw an exception:`);
test.safeGet();
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers