Skip to content

Instantly share code, notes, and snippets.

@carlosspohr
Last active August 29, 2015 14:13
Show Gist options
  • Save carlosspohr/aa3b51583159f14b70a0 to your computer and use it in GitHub Desktop.
Save carlosspohr/aa3b51583159f14b70a0 to your computer and use it in GitHub Desktop.
A simple script to help you when you need to get some nested property using strings, special when you are inside reflections.
Object.byString = function(o, s) {
s = s.replace(/\[(\w+)\]/g, '.$1');
s = s.replace(/^\./, '');
var a = s.split('.');
while (a.length) {
var n = a.shift();
if (n in o) {
o = o[n];
} else {
return;
}
}
return o;
};
var cliente = {
id: 1,
nome: "Js",
contacts:{
phone: "55-45-0000-0000",
cellphone: "55-55-5555-5555",
mail:"js@js.com"
}
};
var desiredProperty = "cliente.contacts.phone"
// by reflection.
console.log(Object.byString(cliente, desiredProperty));
// normal way
console.log(cliente.contacts.phone);
// results.
// "55-45-0000-0000"
// "55-45-0000-0000"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment