2016-03-03 69 views
0

如果有一個數據結構,像這樣:過濾JSON用下劃線

"items": 
     { 
     "Groups":[ 
      { 
       "title":"group 1", 
       "SubGroups":[ 
        { 
        "title":"sub1", 
        "id" : "1", 
        "items":[ 
         { 
          "title":"Ajax request 1", 
         }, 
         { 
          "title":"Ajax request 2", 
         } 
        ] 
        }, 
        { 
        "title":"sub2", 
        "id" : "2", 
        "items":[ 
         { 
          "title":"Ajax request 3", 
         }, 
         { 
          "title":"Ajax request 4", 
         } 
        ] 
        } 
       ] 
      } 
     ] 

我如何拔出基於ID的子組中的所有項目?香港專業教育學院TREID使用發現,像這樣:

var res1 = _.where(listing.items,{id:"2"}); 

卻得到一個空數組返回

感謝

+3

你有第一次解析你的'JSON'值?你不能直接在'JSON'上使用下劃線,而是在javascript對象上使用下劃線 – cl3m

+0

嗨,是的,它已經是一個JavaScript對象了 – DavidB

+1

你需要更深入的搜索,比這個更加深入 – charlietfl

回答

2

嘗試針對亞組陣列,然後搜索你在那裏要的ID。然後應該返回該子組的屬性。

var obj = { 
    "Groups": [{ 
     "title": "group 1", 
     "SubGroups": [{ 
      "title": "sub1", 
      "id": "1", 
      "items": [{ 
       "title": "Ajax request 1", 
      }, { 
       "title": "Ajax request 2", 
      }] 
     }, { 
      "title": "sub2", 
      "id": "2", 
      "items": [{ 
       "title": "Ajax request 3", 
      }, { 
       "title": "Ajax request 4", 
      }] 
     }] 
    }] 
} 

再找到這樣

_.where(obj.Groups[0].SubGroups, { 
    'id': '2' 
}); 

只是測試,這似乎工作

+0

這真是太好了,實際上,我將需要搜索多個頂級組,我如何搜索所有組而不是第一組? – DavidB

+1

你可以使用_.each循環遍歷每個組,並搜索其中的值 - 請參閱https://jsfiddle.net/Lcxsqdbm/ – woolm110

+0

謝謝woolm110 - 這就是完美 – DavidB