我有嵌套的JSON对象,例如
{"baseball": {"mlb": {"regular": {"_events": [{"start_time": "2011-07-31 17:35", "lines": [{"comment": "", "coeff": "2.35", "title": "2", "old_coeff": "2.35", "is_main": true}, {"comment": "", "coeff": "1.59", "title": "2", "old_coeff": "1.59", "is_main": true}, {"comment": "", "coeff": "1.59", "title": "2", "old_coeff": "1.59", "is_main": true}, {"comment": "", "coeff": "2.35", "title": "2", "old_coeff": "2.35", "is_main": true}], "members": ["atlanta", "florida"] } ] }}}}
而且我需要获取_events数组并对其进行解析。但是我不知道_events之前的单元格中的内容以及它们的状态。如何使用这种结构?
function recursiveGetProperty(obj, lookup, callback) { for (property in obj) { if (property == lookup) { callback(obj[property]); } else if (obj[property] instanceof Object) { recursiveGetProperty(obj[property], lookup, callback); } } }
就像这样使用它:
recursiveGetProperty(yourObject, '_events', function(obj) { // do something with it. });
这是一个有效的jsFiddle:http : //jsfiddle.net/ErHng/( 注意 :它会输出到控制台,因此您需要Ctrl+Shift+J/ Cmnd+Option+I在chrome中或在Firefox中打开firebug,然后重新运行它)
Ctrl+Shift+J
Cmnd+Option+I