gpt4 book ai didi

javascript - 隔离 JSON 中具有相似属性的对象

转载 作者:行者123 更新时间:2023-12-02 21:01:05 26 4
gpt4 key购买 nike

我有一个像这样的 JSON 对象:

[
{"Subject": "Physics", "Active": 48, "Date": "2020-01-22T00:00:00Z"},
{"Subject": "Chemistry", "Active": 45, "Date": "2020-01-22T00:00:00Z"},
{"Subject": "Mathematics", "Active": 40, "Date": "2020-01-22T00:00:00Z"},
{"Subject": "English", "Active": 41, "Date": "2020-01-23T00:00:00Z"},
{"Subject": "Chemistry", "Active": 46, "Date": "2020-01-23T00:00:00Z"},
{"Subject": "Mathematics", "Active": 42, "Date": "2020-01-24T00:00:00Z"},
{"Subject": "Chemistry", "Active": 40, "Date": "2020-01-24T00:00:00Z"},
{"Subject": "Physics", "Active": 44, "Date": "2020-01-24T00:00:00Z"},
{"Subject": "Hindi", "Active": 38, "Date": "2020-01-24T00:00:00Z"},
{"Subject": "English", "Active": 41, "Date": "2020-01-25T00:00:00Z"},
{"Subject": "Hindi", "Active": 42, "Date": "2020-01-25T00:00:00Z"},
{"Subject": "Chemistry", "Active": 33, "Date": "2020-01-26T00:00:00Z"},
{"Subject": "Mathematics", "Active": 35, "Date": "2020-01-26T00:00:00Z"}
]

我需要通过根据日期添加事件来隔离这些数据。然后我需要将它插入另一个对象数组中。像这样的事情:

[{
"Active": 133,
"Date": "2020-01-22T00:00:00Z"
},
{
"Active": 87,
"Date": "2020-01-23T00:00:00Z"
},
{
"Active": 164,
"Date": "2020-01-24T00:00:00Z"
},
{
"Active": 83,
"Date": "2020-01-25T00:00:00Z"
},
{
"Active": 68,
"Date": "2020-01-26T00:00:00Z"
}]

最佳答案

这是我的建议

datas = [
{"Subject": "Physics", "Active": 48, "Date": "2020-01-22T00:00:00Z"},
{"Subject": "Chemistry", "Active": 45, "Date": "2020-01-22T00:00:00Z"},
{"Subject": "Mathematics", "Active": 40, "Date": "2020-01-22T00:00:00Z"},
{"Subject": "English", "Active": 41, "Date": "2020-01-23T00:00:00Z"},
{"Subject": "Chemistry", "Active": 46, "Date": "2020-01-23T00:00:00Z"},
{"Subject": "Mathematics", "Active": 42, "Date": "2020-01-24T00:00:00Z"},
{"Subject": "Chemistry", "Active": 40, "Date": "2020-01-24T00:00:00Z"},
{"Subject": "Physics", "Active": 44, "Date": "2020-01-24T00:00:00Z"},
{"Subject": "Hindi", "Active": 38, "Date": "2020-01-24T00:00:00Z"},
{"Subject": "English", "Active": 41, "Date": "2020-01-25T00:00:00Z"},
{"Subject": "Hindi", "Active": 42, "Date": "2020-01-25T00:00:00Z"},
{"Subject": "Chemistry", "Active": 33, "Date": "2020-01-26T00:00:00Z"},
{"Subject": "Mathematics", "Active": 35, "Date": "2020-01-26T00:00:00Z"}
];

function segregate(datas) {
return datas.reduce((c, data) => {
if (!c[data.Date]) {
c[data.Date] = {
Active: data.Active,
Date: data.Date,
};
} else {
c[data.Date].Active += data.Active;
}
return c;
}, {});

}

console.log(segregate(datas));

希望这会有所帮助

关于javascript - 隔离 JSON 中具有相似属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61354537/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com