使用下划线从JSON obj收集数据以创建位置数组

时间:2014-02-25 14:17:19

标签: javascript jquery json underscore.js

我想知道是否有人能够帮助解决这个问题。

我正在使用下划线和大量JSON数据,并希望提取所有不同的事件位置..

是否可以使用此结构在所有事件位置创建数组? (请看obj的图像)

我不确定如何循环获取event_location和event_location_id每天推送到一个数组(如果还没有) - 事件......

基本上我最终需要的是像......这样的列表。

[event_location_id: 1, event_location: somewhere]

enter image description here

提前感谢你提供任何帮助。

注意当前阵列结果[Alberto Montellano] enter image description here

2 个答案:

答案 0 :(得分:0)

您可以使用下划线库的.each功能。 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} ]

我希望它有所帮助。

答案 1 :(得分: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];
        });