2011-11-23 51 views
0

我有數據:如何通過JSON中的類別獲取項目的數據?

var category = [ 
    {id:0, name : "category_1"} , 
    {id:2, name : "category_2"}, 
]; 

var items = [ 
    {id:0, name : "a", category_id : 0} , 
    {id:1, name : "b", category_id : 1} , 
    {id:2, name : "c", category_id : 0}, 
    {id:3, name : "d", category_id : 1} 
]; 

我的問題是:如何才能得到items.namecategory.name通過類別items.category_id? 感謝您的幫助

+0

對不起,在jquery中的數據是JSON – user1061604

回答

0

在這裏你有兩個功能來查找類別ID的項目和類別的ID

var findItemByCategoryId = function(id) { 
    var i = null; 
    var result = [] 
    for (i = 0; items.length > i; i += 1) { 
     if (items[i].category_id === id) { 
      result.push(items[i]); 
     } 
    } 
    return result; 
}; 

// example: 
// categoryItems = findItemByCategoryId(0); 
// for(var i=0; i<items.length; i++) { 
//  //alert(items[i].name) 
// } 

var findCategoryById = function(id) { 
    var i = null; 
    for (i = 0; category.length > i; i += 1) { 
     if (category[i].id === id) { 
      return category[i]; 
     } 
    } 
}; 
// example: 
// alert(findCategoryById(0).name); 
1

JSON不是SQL數據庫,因此您不需要有兩個JSON結構或文件。 就改寫,如:

{ 
    '0': {"name" : "category_1", 
     "items": { 
      "0": "a", 
      "2": "c" 
     } 
     }, 
    '2': {"name" : "category_2", 
     "items": { 
      "2": "c", 
      "3": "d" 
     } 
     } 
} 
+0

謝謝!它適用於我 – user1061604

0

在JavaScript試試這個:

var item = items[0]; // Get the first item 

var cat = null; 
$.each(category, function(k, v){ 
    if(v.id == item.category_id) 
    { 
     cat = this; 
     return false; // Return because we got a match 
    } 
}); 

// If we got a match 
if(cat) 
    alert(cat.name); 
0
var result = []; 
var temp = []; 

$.each(category, 
    function(index, c) { 
     $.each(items, 
     function(i, value) { 
      if (value.category_id == c.id) { 
       temp.push(value.name); 
      } 
     }); 
     result.push({ 
      category_name: c.name, 
      values: temp 
     }); 
     temp = []; 
}); 
console.log(result); 
+0

謝謝!它適用於我:d – user1061604

0

對於此數據:

var category = [ 
{id:0, name : "category_1"} , 
{id:2, name : "category_2"} 
]; 

var items = [ 
{id:0, name : "a", category_id : 0} , 
{id:1, name : "b", category_id : 1} , 
{id:2, name : "c", category_id : 2}, 
{id:3, name : "d", category_id : 3} 
]; 

你有這樣的功能:

 function getItemName(cat_id){ 
      $.each(items, function(i, item){ 
       if(item.category_id == cat_id) 
        return item.name; 
      }) 
     } 

電話與類別ID是這樣的:getItemName(2); 它會回報您的項目名稱。

相關問題