【问题标题】:sorting json by years / dates (JSON/nodeJS)按年份/日期排序 json (JSON/nodeJS)
【发布时间】:2014-06-10 20:48:50
【问题描述】:

嘿,我有这样的 json

news
    {
        title: 'hello world',
        body: 'bla bla bla',
        publish_date: '2014-04-12'
    },
    {
        title: 'hello world',
        body: 'bla bla bla',
        publish_date: '2014-04-30'
    }   
    {
        title: 'hello world 2',
        body: 'bla bla bla',
        publish_date: '2015-02-30'
    },
    {
        title: 'hello world 2',
        body: 'bla bla bla',
        publish_date: '2015-02-17'
    },
    {
        title: 'hello world 2',
        body: 'bla bla bla',
        publish_date: '2015-05-30'
    }

我想按“年”和“月”的“发布日期”对其进行排序,如下所示:

{
    2014: [{
        04: [{
            {
                title: 'hello world',
                body: 'bla bla bla',
                publish_date: '2014-04-12'
            },
            {
                title: 'hello world',
                body: 'bla bla bla',
                publish_date: '2014-04-30'
            }   
        }]
    ]}
    2015: [{
        02: [{
            {
                title: 'hello world 2',
                body: 'bla bla bla',
                publish_date: '2015-02-30'
            },
            {
                title: 'hello world 2',
                body: 'bla bla bla',
                publish_date: '2015-02-17'
            },
        }],
        05: [{
            {
                title: 'hello world 2',
                body: 'bla bla bla',
                publish_date: '2015-05-30'
            }
        ]}
    }]
}

所以我找到了这个 sort JSON by date 按日期对我的 json 进行排序,然后我得到了这个 http://lodash.com/docs#forEach 运行我的主要 json 但我如何“拆分”日期以便完成它?把它分成几年然后一个月?以及如何“推入”我的新排序 json ?我怎样才能确保每年都不会错过任何一个月? 一个方向或无论如何完成它会很棒:)

非常感谢!

【问题讨论】:

    标签: javascript json node.js sorting date


    【解决方案1】:

    最好将这些日期转换为实际的日期对象,然后更容易更清楚地访问年份和月份,如下所示:http://jsfiddle.net/RAkkk/

    为了简洁起见,我使用了原生 forEach,但 Lodash 也可以这样做。

    var json = [
    {
        title: 'hello world',
        body: 'bla bla bla',
        publish_date: '2014-04-12'
    },
    {
        title: 'hello world',
        body: 'bla bla bla',
        publish_date: '2014-04-30'
    },   
    {
        title: 'hello world 2',
        body: 'bla bla bla',
        publish_date: '2015-02-30'
    },
    {
        title: 'hello world 2',
        body: 'bla bla bla',
        publish_date: '2015-02-17'
    },
    {
        title: 'hello world 2',
        body: 'bla bla bla',
        publish_date: '2015-05-30'
    }
    ];
    
    var newJson = {};
    
    json.forEach(function (item) {
        var date = new Date(item.publish_date),
            year = date.getUTCFullYear(),
            month = date.getUTCMonth() + 1;
    
        newJson[year] = newJson[year] || {};
        newJson[year][month] = newJson[year][month] || [];
        newJson[year][month].push(item);
    });
    
    console.log(newJson);
    

    然后在目标对象中断言它们的存在并创建并推送或简单地推送是相当直接的,如小提琴所示。

    此外,如果您想实际对月份组数组进行排序,您可以像这样比较日期:

    var a = new Date('2015-02-17');
    var b = new Date('2015-05-30');
    console.log(a < b);
    

    【讨论】:

    • 完美!非常感谢!我只是有一个问题是||代表 ? newJson[year] = newJson[year] **||** {}; 我知道它是“或”的运算符,但它在这里做什么?就像如果?真假 ?请解释一下:)谢谢!
    • @greW - 如果 newJson[year] 尚不存在,则将其分配给空对象(如果已存在则保持不变)。否则,接下来的两行将产生未定义的错误。如果尚未设置,则在后续行中为 newJson[year][month] 创建一个最初为空的数组。
    【解决方案2】:

    在这种情况下你想reduce。要拆分日期,您可以使用 Date 解析它并从中获取年份和月份。然后在您的地图回调中,您可以根据该值添加正确的值。

        var myRes = _.reduce(arr, function(result, elem, key) {
          // get the year and month strings
          var year = getYearFromDateString(elem.publish_date)
          var month = getMonthFromDateString(elem.publish_date)
          // check and initiallize the object structure
          if (result[year] == null) result[year] = {}
          if (result[year][month] == null) result[year][month] = []
          result[year][month].push(elem)
          return result
        }, {} /*this is the initially empty object, the result */)
    

    【讨论】:

    • 你能解释一下我该如何使用 reduce 吗?我必须将日期与.split("-") 分开,但我看不到 reduce 对我的帮助,谢谢!
    【解决方案3】:

    循环遍历原始json:

    var newJson = [];
    for (var i in originalJson) {
        var year = originalJson[i].publish_date.substring(0,4);
        var month = originalJson[i].publish_date.substring(5,2);
        if (typeof newJson[year] == "undefined") newJson[year] = [];
        if (typeof newJson[year][month] == "undefined") newJson[year][month] = [];
        newJson[year][month].push(originalJson[i]);
    }
    

    我没有尝试过这个..但可能有效:D

    【讨论】:

    • 好吧,我试过这个,更像是:pastebin.com/ezezNwME,我得到的只是很多:,,,,,,,,,,[]] 不确定,为什么..我试着替换 mynew = [];到 mynew = {};然后我得到: { '2014': [ ] } { '2014': [ ], '2015': [ ] } 谢谢你的回答! ——
    【解决方案4】:
    function custom_sort(a, b) {
        return new Date(a.publish_date).getTime() - new Date(b.publish_date).getTime();
    }
    var json = [
    {
        title: 'hello world',
        body: 'bla bla bla',
        publish_date: '2014-04-12'
    },
    {
        title: 'hello world',
        body: 'bla bla bla',
        publish_date: '2014-04-30'
    },   
    {
        title: 'hello world 2',
        body: 'bla bla bla',
        publish_date: '2015-02-30'
    },
    {
        title: 'hello world 2',
        body: 'bla bla bla',
        publish_date: '2015-02-17'
    },
    {
        title: 'hello world 2',
        body: 'bla bla bla',
        publish_date: '2015-05-30'
    }
    ];
    
    json .sort(custom_sort);
    

    【讨论】:

      猜你喜欢
      • 2018-01-25
      • 1970-01-01
      • 2022-08-11
      • 1970-01-01
      • 1970-01-01
      • 2012-03-08
      • 1970-01-01
      • 2021-12-28
      • 2012-07-04
      相关资源
      最近更新 更多