搜索包含多个对象和数组的Object的最佳方法

时间:2012-12-04 19:50:19

标签: javascript arrays sorting object

我尝试了几种使用indexOf和if(x in y)的方法,似乎没有一种方法能够完全符合我的要求。

我需要浏览多个对象,并根据对象找到特定的数字/时间戳/日期。这是我的对象控制台的屏幕截图。

有什么想法? enter image description here

特别是当我第一次获取数据时,我从API响应中提取所有时间戳(在日期/时间上发布)。使用该时间戳数组,我试图从所有响应中找到最新发布的对象。

以下是一些屏幕截图:

Twitter created_at时间戳 Twitter created_at timestamp

Tumblr timestamp Tumblr timestamp

和我的日期数组 enter image description here

我的代码用于提取信息并对其进行排序。

//AJAX CALLS
$.when(
    //Bitter Syndrome
    $.ajax({
        type: "GET",
        dataType: "jsonp",
        cache: false,
        url: "http://api.tumblr.com/v2/blog/"+bittersymdrome_tumblr+"/posts/?api_key="+tumblr_apiKey,
        success: function(data){
            delete data.meta; delete data.response.blog;
            blogs.content.push(data);
        }
    }),

    //moundsMusic Tumblr
    $.ajax({
        type: "GET",
        dataType: "jsonp",
        cache: false,
        url: "http://api.tumblr.com/v2/blog/"+moundsmusic_tumblr+"/posts/?api_key="+tumblr_apiKey,
        success: function(data){
            delete data.meta; delete data.response.blog;
            blogs.content.push(data);
        }
    }),

    //GateWayDrugSTL Tumblr
    $.ajax({
        type: "GET",
        dataType: "jsonp",
        cache: false,
        url: "http://api.tumblr.com/v2/blog/"+gatewaydrug_tumblr+"/posts/?api_key="+tumblr_apiKey,
        success: function(data){
            delete data.meta; delete data.response.blog;
            blogs.content.push(data);
        }
    }),

    //GateWayDrugSTL Twitter
    $.ajax({
        type: "GET",
        dataType: "jsonp",
        cache: false,
        url: "http://api.twitter.com/1/statuses/user_timeline.json?user_id="+gatewaydrug_twitter,
        success: function(data){
            blogs.content.push( data );
            /*var time = data[0].created_at;
            gwdtwDate = Date.parse(time)/1000;*/
        }
    })
).done( function(){
    //Get and Sort Dates most recent first.
    for(var i=0;i<blogs.content.length;i++){
        if(!blogs.content[i].length){
            for(var e=0; e<blogs.content[i].response.posts.length; e++){
                blogs.dates.push(blogs.content[i].response.posts[e].timestamp);
            }
        } else {
            for (var e = 0; e<blogs.content[i].length; e++){
                var time = blogs.content[i][e].created_at;
                gatewaydrug_twitter_date = Date.parse(time)/1000;
                blogs.dates.push(gatewaydrug_twitter_date);
            }
        }
    }
    blogs.dates.sort(function(a,b){return b-a});
    console.log( blogs );

    for(var i=0,len=blogs.dates.length; i<len;i++){

    }
});

Here是指向测试服务器的实时链接,您可以在其中查看浏览器控制台中的对象:http://thehivestl.com/test/

1 个答案:

答案 0 :(得分:1)

不要在同一个数组中混合使用不同的对象类型,而是先将它们标准化。此外,您不需要使用全局blogs变量,而是正确使用Deferred。

function handleTumblrResponse(data) {
    delete data.meta;          // actually, you don't
    delete data.response.blog; // need those
    var resultdates = [];
    for (var e=0; e<data.response.posts.length; e++)
        resultdates.push(data.response.posts[e].timestamp);
    return resultdates;
}
function handleTwitterResponse(data) {
    var resultdates = [];
    for (var e = 0; e<data.length; e++){
        var timesting = data[e].created_at;
        var date = Date.parse(time)/1000;
        resultdates.push(date);
    }
    return resultdates;
}
$.when(
    // those get… functions are the plain ajax calls, no success handlers
    getBitterSyndromeAjax().then(handleTumblrResponse),
    getMoundsMusicTumblr().then(handleTumblrResponse),
    getGateWayDrugSTLTumblr().then(handleTumblrResponse),
    getGateWayDrugSTLTwitter().then(handleTwitterResponse)
).done(function(bitterSyndrom, moundsMusic, drugsTumb, drugsTwit) {
    // concat the four arrays to one
    var dates = Array.prototype.concat.apply([], arguments);
    dates.sort(function(a,b){return b-a});
    // do something with the timestamps
});

顺便说一句,我很确定Date.parse无法处理那种奇怪的Twitter格式。相反,使用

function fromDateString(str) {
    var res = str.match(/(\S{3})\s(\d{2})\s(\d+):(\d+):(\d+)\s(?:([+-])(\d\d)(\d\d)\s)?(\d{4})/);
    if (res == null)
        return NaN; // or something that indicates it was not a DateString
    var time = Date.UTC(
      +res[9],
      {"Jan":0,"Feb":1,"Mar":2, …, "Dec":11}[res[1]] || -1,
      +res[2],
      +res[3],
      +res[4],
      +res[5], 
    );
    if (res[6] && res[7] && res[8]) {
        var dir = res[6] == "+" ? -1 : 1,
            h = parseInt(res[7], 10),
            m = parseInt(res[8], 10);
        time += dir * (h*60+m) * 60000;
    }
    return time;
}