Retrieve json object based on given value
本问题已经有最佳答案,请猛点这里访问。
从下面的json,我如何根据给定的applicationName检索对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | { "apps": [ { "applicationName":"myTestApp", "keys": [ { "key":"app-key", "value":"ZDM0" }, { "key":"env-key", "value":"YTE1Mm" } ] }, { "applicationName":"hello", "keys": [ { "key":"app-key", "value":"ZjIwZT" }, { "key":"env-key", "value":"MDExMTc5N2" } ] } ] } |
因此,如果我的输入是myTestApp,我想获取myTestApp对象
1 2 3 4 5 6 7 8 9 10 11 12 13 | { "applicationName":"myTestApp", "keys": [ { "key":"app-key", "value":"ZDM0" }, { "key":"env-key", "value":"YTE1Mm" } ] } |
这应该做的伎俩:
(假设您的
1 2 3 4 5 6 7 | var result = data.apps.filter(function(app){ return app.applicationName ==="myTestApp"; }); if(result.length){ // If there are any results, then console.log(result[0]) // `result[0]` is the app with the right name. } |
var jsonData; //把你的json数据放在这里
1 2 3 4 5 6 7 8 | var appsArr = jsonData.apps; for (var i in appsArr) { if(appsArr[i].applicationName =="myTestApp") { var requiredObj = appsArr[i]; break; } } |
您应该遍历JSON数组并检查
http://jsfiddle.net/bcudcyf6/1/
1 2 3 4 5 | var object = yourJSONdata; for(var i in object.apps){ if("hello" == object.apps[i].applicationName) alert(i); } |
如果您的JSON太大,您还可以使用像Defiant(http://www.defiantjs.com/)这样的外部JavaScript库,这使得搜索变得简单快捷