删除日期已过的 JSON 个对象

Remove JSON Objects With Date Already Passed

我正在尝试通过一个名为 "Event Date." 的元字段对 Shopify 博客帖子进行排序 我调用了我的 articles.JSON 但它没有随 metafields.JSON 一起提供,所以我必须接受它数组并通过 foreach 函数将元字段附加到每篇文章。

每篇文章的 metafields.json 是这样设置的:

{  
   "metafields":[  
      {  
         "id":5994805788772,
         "namespace":"global",
         "key":"Event-Date",
         "value":"1549256400",
         "value_type":"string",
         "description":null,
         "owner_id":15977611364,
         "created_at":"2019-02-06T18:31:44-05:00",
         "updated_at":"2019-02-06T18:31:44-05:00",
         "owner_resource":"article"
      },
      {  
         "id":5994805821540,
         "namespace":"global",
         "key":"Event-Time",
         "value":"6:00pm - 8:00pm",
         "value_type":"string",
         "description":null,
         "owner_id":15977611364,
         "created_at":"2019-02-06T18:31:45-05:00",
         "updated_at":"2019-02-06T18:31:45-05:00",
         "owner_resource":"article"
      },
      {  
         "id":6010564542564,
         "namespace":"global",
         "key":"Location",
         "value":"18th Street Location",
         "value_type":"string",
         "description":null,
         "owner_id":15977611364,
         "created_at":"2019-02-07T13:16:05-05:00",
         "updated_at":"2019-02-07T14:05:08-05:00",
         "owner_resource":"article"
      }
   ]
}

我如何附加下面的 metafields.JSON:

var request = new XMLHttpRequest();

request.open('GET', '/admin/blogs/43130421348/articles.json');
request.responseType = 'json';
request.send();

request.onload = function() {
    var articleList = request.response; 
    var articleArray = articleList.articles;
    var date = new Date();
    var ticks = Math.floor(date.getTime() / 1000);
    var count = 0;
    articleArray.forEach(function(entry,index, object){
    var metaRequest = new XMLHttpRequest();
    metaRequest.open('GET', '/admin/blogs/43130421348/articles/'+ entry.id + '/metafields.json');
    metaRequest.responseType = 'json';
    metaRequest.send();
    console.log(index);

    metaRequest.onload = function() {
        var articleMetaObj = metaRequest.response;
        var articleMetaArr = articleMetaObj.metafields;
        entry.metafields = articleMetaArr; 
        var eventDate = entry.metafields[0].value;
   }

 });

};

我现在正试图删除任何日期 ("Key": "Event-Date") 与当前日期相比已经过去的文章。我查看了以下关于在 foreach 循环中删除对象的 Stack Overflow Post,但 none 的解决方案证明实际上删除了所有文章。它偶尔会清除所有对象,但有时会留在其中一个对象中。

我也试过一个数组过滤器,但是当我使用它时,我得到的只是一个空数组。我现在一直坚持这个问题,所以非常感谢任何解决它的帮助。

你的条目是文章吗?那么你可以忽略使用:

request.onload = function() {
var articleList = request.response; 
var articleArray = articleList.articles;
var date = new Date();
var ticks = Math.floor(date.getTime() / 1000);
var count = 0;
articleArray.forEach(function(entry,index, object){
   if(entry.'Key' !== 'Event-Date'){
        var metaRequest = new XMLHttpRequest();
        metaRequest.open('GET', '/admin/blogs/43130421348/articles/'+ entry.id + '/metafields.json');
        metaRequest.responseType = 'json';
        metaRequest.send();
        console.log(index);

        metaRequest.onload = function() {
        var articleMetaObj = metaRequest.response;
        var articleMetaArr = articleMetaObj.metafields;
        entry.metafields = articleMetaArr; 
        var eventDate = entry.metafields[0].value;
       }
   }
});

我认为最简单的方法是等到附加所有元数据,然后在全部完成后,使用 articleArray.filter 删除不需要的元数据。为此,您有两个选择:

选项 1 - 旧方法 (setInterval)

在这里,我们在检索元数据时保持计数,并创建一个时间间隔来检查它们何时全部完成。完成后,将调用一个函数(完成)以允许继续处理。

var request = new XMLHttpRequest();

request.open('GET', '/admin/blogs/43130421348/articles.json');
request.responseType = 'json';
request.send();

request.onload = function () {
    var articleList = request.response;
    var articleArray = articleList.articles;
    var date = new Date();
    var ticks = Math.floor(date.getTime() / 1000);
    var count = 0;  //to keep track of how many metafields have been retrieved
    var checkInterval = null;

    articleArray.forEach(function (entry, index) {
        var metaRequest = new XMLHttpRequest();
        metaRequest.open('GET', '/admin/blogs/43130421348/articles/' + entry.id + '/metafields.json');
        metaRequest.responseType = 'json';
        metaRequest.send();
        console.log(index);

        metaRequest.onload = function () {
            var articleMetaObj = metaRequest.response;
            var articleMetaArr = articleMetaObj.metafields;
            entry.metafields = articleMetaArr;
            count++;
        };
    });

    //Function to continue processing
    var finish = function () {
        articleArray = articleArray.filter(a => new Date(a.metafields[0].value).getTime() < date.getTime());
        //Continue on...
    };

    //Wait until all metafields are retrieved to continue
    checkInterval = setInterval(function () {
        if (count === articleArray.length - 1) {
            clearInterval(checkInterval);
            finish();
        }
    }, 500);
};

选项 2 - 新的 Razmatazz(承诺和 async/await)

Promises and async/await 允许在处理异步操作时编写一些更漂亮的代码。

如果您想使用这些,我建议您深入研究文档以更加熟悉,但这是您的任务的样子。

//Functions that return Promises can be awaited...
var get = url => new Promise((resolve, reject) => {
    var request = new XMLHttpRequest();
    request.open('GET', url);
    request.responseType = 'json';
    //resolve is called when successful
    request.onload = () => resolve(request.response);
    //reject is called when there's a problem
    request.onerror = err => reject(err);
    request.send();
});

//await keyword must appear in an async function
var getArticles = async () => {
    var articleList = await get('/admin/blogs/43130421348/articles.json');
    return articleList.articles;
};

//Promise.all takes an array of promises and resolves when all of them are finished
//This lets you skip the messy setInterval stuff
var getArticleMetafields = async articles => {
    var requests = [];
    articles.forEach(a => {
        var url = '/admin/blogs/43130421348/articles/' + a.id + '/metafields.json';
        var promise = get(url);
        requests.push(promise);
    });
    var responses = await Promise.all(requests);
    responses.forEach((response, i) => {
        articles[i].metafields = response.metafields;
    });
    return articles;
};

//Notice the async on the handler
document.addEventListener('DOMContentLoaded', async () => {
    var articles = await getArticles();
    articles = await getArticleMetafields(articles);
    var date = new Date();
    articles = articles.filter(a => new Date(a.metafields[0].value) < date);
    //Continue...
});

希望这对您有所帮助。干杯!