2015-08-29 71 views
-1

說我有這個隨機JSON文件:獲得一個變量從一個JSON裏面相關的數據裏面

{ 
    "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" 
    } 
    ] 
} 

我怎樣才能獲得的類別名稱,如果我有的categoryID?

大加讚賞,

托馬斯

回答

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; 

BTW:過濾器可能會返回一個空的集合,如果它沒有找到結果。

+0

非常感謝你! – ThomasG

+0

如果我可能會問,[0]的功能是什麼? – ThomasG

+0

filter將返回一個數組,並且由於您知道parentId是唯一的,所以它將始終返回一個具有單個元素的數組。這就是我使用[0]的原因。 –

相關問題