从json里面获取数据依赖于里面的变量

时间:2015-08-29 22:43:55

标签: javascript json

说我有这个随机的json文件:

d = json.loads(json_string)

如果我有categoryID,我怎样才能获得categoryName?

非常感谢,

托马斯

1 个答案:

答案 0 :(得分:1)

使用Array.prototype.filter

var obj =  {
  "categoryName": "Appetizers & Sides",
  "categories": [
    {
      "categoryID": "294",
      "parentID": "304",
      "subjectID": "7",
      "categoryName": "Apps and Side Dishes (Laura)",
      "categoryDescription": "Learn to make amazing appetizers and side dishes with Laura in the Kitchen.",
      "videosCount": "101",
      "forumCategoryID": "163"
    },
    {
      "categoryID": "285",
      "parentID": "304",
      "subjectID": "7",
      "categoryName": "Side Dishes",
      "categoryDescription": "Side dish recipes for salads, vegetables, sauces with Hilah cooking.",
      "videosCount": "38",
      "forumCategoryID": "163"
    }
  ]
};
var parentId = "304";
var catId = obj.categories.filter(function(item){ return item.parentID === parentId })[0].categoryID;

顺便说一句:过滤器可能会返回一个空集合,如果它没有找到结果。