将每个传入的响应连接到对象属性

时间:2018-09-09 17:06:31

标签: javascript arrays json object

我想将resnews的每个响应连接到称为newsObj.getNews的对象属性。

页面首次加载时,API会调用;向下滚动时,API会继续加载。我想将每个传入的响应(限制为10个)添加到对象属性。

现在,每次调用API时,它都会与newsObj.getNews中的数据重叠,并且仅显示10。

  $.ajax({
    method: 'GET',
    url: url,
    data: newsParams,
    success: function(resnews) {
        // app.preloader.hide();
        if(resnews.status == 'ok') {
            if(type=="relevancy"){                      
                newsObj.getNews = resnews.articles; // overlapping my response 
                console.log(typeof resnews.articles); //returns object
                _self.renderNewsInUIAppend(resnews.articles, type)
            } else {
                newsObj.popular = resnews.articles;
                console.log(typeof newsObj);//returns object
                _self.renderNewsInUIAppend(resnews.articles, type);
            }
        } else {
            console.warn("There was error fetching error.");
        }
    }
})

我对newsObj.getNews的回复

enter image description here

1 个答案:

答案 0 :(得分:1)

typeof []将给出“对象”,因为数组是一个对象

console.log(typeof [])

您可以从here

中找到解释。

您正在循环对象数组以显示数据。因此,您可以将新数据与旧数据连接起来,如下所示:

var latestNews;
var newsObj = {};
var resNews = {};
resNews.articles = [{id: 1}, {id: 2}];

// At first newsObj.getNews is undefined like below
console.log(newsObj.getNews);

// So you need to do like below
if (typeof newsObj.getNews !== "undefined") {
  latestNews = newsObj.getNews.concat(resNews.articles);
  newsObj.getNews = latestNews;
} else {
  newsObj.getNews = resNews.articles;
}

console.log(newsObj.getNews);

// New news
resNews.articles = [{id: 3}, {id: 4}];

setTimeout(function () {
  latestNews = newsObj.getNews.concat(resNews.articles);
  newsObj.getNews = latestNews;
  console.log(newsObj.getNews);
}, 1000);