Skip to content

Instantly share code, notes, and snippets.

@sebald
Created September 25, 2013 14:36
Show Gist options
  • Select an option

  • Save sebald/6700555 to your computer and use it in GitHub Desktop.

Select an option

Save sebald/6700555 to your computer and use it in GitHub Desktop.
A Pen by Sebastian.
<h1>Look in the console!</h1>

Robust getter Fn

Get property of an object no matther if it is deeply nested or doesn't even exist.

A Pen by Sebastian on CodePen.

License.

(function ( undefined ) {
// Fixture
var data = {
"created": "2013-09-25T13:28:36.562Z",
"persons" : [
{
"id": 0,
"isActive": true,
"age": 20,
"name": "Rodgers Steele",
"gender": "male",
"email": "[email protected]",
"phone": "+1 (990) 474-2484",
"address": "821 Freeman Street, Cornfields, Connecticut, 567"
},
{
"id": 1,
"isActive": true,
"age": 35,
"name": "Haney Mcintosh",
"gender": "male",
"email": "[email protected]",
"phone": "+1 (818) 454-2993",
"address": "761 Beach Place, Shrewsbury, Missouri, 2955"
},
{
"id": 2,
"isActive": false,
"age": 38,
"name": "Alisha Patterson",
"gender": "female",
"email": "[email protected]",
"phone": "+1 (825) 548-2662",
"address": "847 Sandford Street, Blanco, Tennessee, 1727"
},
{
"id": 3,
"isActive": false,
"age": 38,
"name": "Autumn Avery",
"gender": "female",
"email": "[email protected]",
"phone": "+1 (875) 537-3726",
"address": "729 Seton Place, Vicksburg, Alaska, 4125"
},
{
"id": 4,
"isActive": false,
"age": 37,
"name": "Skinner Baxter",
"gender": "male",
"email": "[email protected]",
"phone": "+1 (845) 582-2520",
"address": "665 Chestnut Street, Berlin, West Virginia, 8698"
},
{
"id": 5,
"isActive": true,
"age": 27,
"name": "Underwood Johnston",
"gender": "male",
"email": "[email protected]",
"phone": "+1 (886) 553-3241",
"address": "951 Crooke Avenue, Taycheedah, New Mexico, 7855"
}
]
};
// Robut getter
// @param {Object} o the object
// @oaram {String} p the property to get
//
// @return {Any} Returns the property if found, "undefined" otherwhise
function getProperty ( o , p ) {
var n = p.replace(/\[(\w+)\]/g, '.$1').match(/^(\w+)\.?(.*)/);
return !n[2] ? o[n[1]] : getProperty(o[n[1]], n[2]);
};
// Use cases
console.log(getProperty( data, 'created' ));
console.log(getProperty( data, 'persons' ));
console.log(getProperty( data, 'persons[1].phone' ));
console.log(getProperty( data, 'persons[2].age' ));
console.log(getProperty( data, 'foo' ));
console.log(getProperty( data, 'persons[1].phone.foo' ));
})( );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment