Skip to content

Instantly share code, notes, and snippets.

@cristoferdomingues
Created November 19, 2018 16:20
Show Gist options
  • Save cristoferdomingues/f77a5bbc7bdd71bb2949b6e703e930d8 to your computer and use it in GitHub Desktop.
Save cristoferdomingues/f77a5bbc7bdd71bb2949b6e703e930d8 to your computer and use it in GitHub Desktop.
Get atributes from object by string
Object.byString = function(o, s) {
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
}
// Usage
var someObject = {
'part1' : {
'name': 'Part 1',
'size': '20',
'qty' : '50'
},
'part2' : {
'name': 'Part 2',
'size': '15',
'qty' : '60'
},
'part3' : [
{
'name': 'Part 3A',
'size': '10',
'qty' : '20'
}, {
'name': 'Part 3B',
'size': '5',
'qty' : '20'
}, {
'name': 'Part 3C',
'size': '7.5',
'qty' : '20'
}
]
};
Object.byString(someObj, 'part3[0].name');
Object.byString(someObj, 'part1.name');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment