2014-02-25 16 views
1

數組是否有人能夠幫助這個..使用JSON OBJ收集數據強調創建的我想知道位置

我使用下劃線和JSON數據的一大塊,並希望所有提取不同的事件地點..

是否有可能創建一個使用此結構的所有事件位置的數組? (請參閱obj的圖像)

我不知道如何來遍歷得到event_location和event_location_id推到一個數組(如果尚未有)爲每一天 - 事件......

所以基本上是我需要的到底是一個列表如..

[event_location_id: 1, event_location: somewhere] 

enter image description here

預先感謝您的任何幫助。

注當前數組結果[阿爾貝託蒙特拉諾] enter image description here

回答

0

您可以使用下劃線庫。每個功能。 http://underscorejs.org/#each

我的建議是:

var arrayResult = []; 
_.each(yourObject.days, function(day, key) { 
    _.each(day.events, function(event, key) { 
      var obj = { 
       event_location_id : event.event_location_id, 
       event_location: event.event_location 
      }; 
      arrayResult.push(obj); 
     }); 
    }); 

你的結果將是:

[{event_location_id: 1, event_location: somewhere}, {event_location_id: 2, event_location: somewhere2}, {event_location_id: 3, event_location: somewhere3} ] 

我希望它能幫助。

+0

它確實非常多,我貼什麼arrayResult看起來像我上面 - 我可以遍歷這個和neaten起來我猜想 - 如果我不能找到更好的創造它。 – Iamsamstimpson

0

只是爲了完整性,這是我的完整的解決方案:

var arrayResult = []; 
_.each(yourObject.days, function(day, key) { 
    _.each(day.events, function(event, key) { 
     var obj = { 
      event_location_id : event.event_location_id, 
      event_location: event.event_location 
     }; 
     arrayResult.push(obj); 
    }); 
}); 


     var uniques = _.map(_.groupBy(arrayResult,function(theEvent){ // returns an unique array of venues 
     if(theEvent.event_location_id > 0) // exclude non-events e.g. id = 0.. 
     { 
      return theEvent.event_location_id;// console.log(theEvent.event_location_id); 
     } 
     }),function(grouped){ 
      return grouped[0]; 
     }); 
相關問題