我想在JavaScript中创建一个新对象以对year进行分组。它将数据存储到年份组中。

我现在拥有的数据:

{
    "8": {
        "date": "2016-02-26",
        "value": "0.89000"
    },
    "7": {
        "date": "2017-02-27",
        "value": "0.94000"
    },
    "6": {
        "date": "2017-06-01",
        "value": "0.94000"
    },
    "5": {
        "date": "2017-08-30",
        "value": "0.94000"
    },
    "4": {
        "date": "2017-11-30",
        "value": "1.01000"
    },
    "3": {
        "date": "2018-02-28",
        "value": "1.01000"
    },
    "2": {
        "date": "2018-06-01",
        "value": "1.01000"
    },
    "1": {
        "date": "2018-08-31",
        "value": "1.01000"
    },
    "0": {
        "date": "2018-11-30",
        "value": "1.16000"
    }
}

我想转换为以下内容:
{
    2016: [
            {
                "date": "2016-02-26",
                "value": "0.89000"
            }
    ],
    2017: [
            {
                "date": "2017-02-27",
                "value": "0.94000"
            },
            {
                "date": "2017-06-01",
                "value": "0.94000"
            },
            {
                "date": "2017-06-01",
                "value": "0.94000"
            },
            {
                "date": "2017-08-30",
                "value": "0.94000"
            }
    ],
    2018: [
            {
                "date": "2018-02-27",
                "value": "0.104000"
            },
            {
                "date": "2018-06-01",
                "value": "1.01000"
            },
            {
                "date": "2018-08-31",
                "value": "1.01000"
            },
            {
                "date": "2018-11-30",
                "value": "1.16000"
            }
    ]
}

更多内容,目的是在此处发布问题。更多内容,目的是在此处发布问题。更多内容,目的是在此处发布问题。更多内容,目的是在此处发布问题。更多内容,目的是在此处发布问题。

最佳答案

您可以使用Object.values将对象转换为数组。使用reduce遍历数组并将其汇总为一个对象。使用substring(0, 4)获取日期字符串的前4个字符。

var obj = {"0":{"date":"2018-11-30","value":"1.16000"},"1":{"date":"2018-08-31","value":"1.01000"},"2":{"date":"2018-06-01","value":"1.01000"},"3":{"date":"2018-02-28","value":"1.01000"},"4":{"date":"2017-11-30","value":"1.01000"},"5":{"date":"2017-08-30","value":"0.94000"},"6":{"date":"2017-06-01","value":"0.94000"},"7":{"date":"2017-02-27","value":"0.94000"},"8":{"date":"2016-02-26","value":"0.89000"}}

var result = Object.values(obj).reduce((c, v) => {
  var y = v.date.substring(0, 4);
  (c[y] = c[y] || []).push(v);
  return c;
}, {});

console.log(result);

10-06 13:47
查看更多