I expanded Andy E's answer so that it can also process arrays:
function getDescendantProp(obj, desc) { var arr = desc.split("."); //while (arr.length && (obj = obj[arr.shift()])); while (arr.length && obj) { var comp = arr.shift(); var match = new RegExp("(.+)\\[([0-9]*)\\]").exec(comp); if ((match !== null) && (match.length == 3)) { var arrayData = { arrName: match[1], arrIndex: match[2] }; if (obj[arrayData.arrName] != undefined) { obj = obj[arrayData.arrName][arrayData.arrIndex]; } else { obj = undefined; } } else { obj = obj[comp] } } return obj; }
There are probably more efficient ways to run Regex, but they are compact.
Now you can do things like:
var model = { "m1": { "Id": "22345", "People": [ { "Name": "John", "Numbers": ["07263", "17236", "1223"] }, { "Name": "Jenny", "Numbers": ["2", "3", "6"] }, { "Name": "Bob", "Numbers": ["12", "3333", "4444"] } ] } }
JohnB Sep 27 '13 at 10:52 on 2013-09-27 10:52
source share