gpt4 book ai didi

javascript - 基于javascript中的多个键对数据进行分组

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:20:28 26 4
gpt4 key购买 nike

收到 JSON 响应

[{
"name": "A1",
"date": "2019-03-13",
"comment": "xyz"
},
{
"name": "A1",
"date": "2019-03-13",
"comment": "abc"
},
{
"name": "B1",
"date": "2019-03-13",
"comment": "pqr"
},
{
"name": "A1",
"date": "2019-03-14",
"comment": "mno"
}
]

预期输出

[
{
"name": "A1",
"date": "2019-03-13",
"data": [
{
"name": "A1",
"date": "2019-03-13",
"comment": "xyz"
},
{
"name": "A1",
"date": "2019-03-13",
"comment": "abc"
}
],
{
"name": "A1",
"date": "2019-03-14",
"data": [
{
"name": "A1",
"date": "2019-03-14",
"comment": "mno"
}
]
},
{
"name": "B1",
"date": "2019-03-13",
"data": [
{
"name": "B1",
"date": "2019-03-13",
"comment": "pqr"
}
]
}
]

我想创建新的 javascript 数组,其中包含唯一的名称和日期及其各自的数据。

有人可以帮我吗?

最佳答案

您可以使用 array#reduce根据 name 对日期进行分组& date在对象累加器中,然后使用 Object.values() 提取所有值.

let data = [{ "name": "A1", "date": "2019-03-13", "comment": "xyz" }, { "name": "A1", "date": "2019-03-13", "comment": "abc" }, { "name": "B1", "date": "2019-03-13", "comment": "pqr" }, { "name": "A1", "date": "2019-03-14", "comment": "mno" } ],
result = Object.values(data.reduce((r,{name,date, comment}) => {
r[name + "_" + date] = r[name + "_" + date] || {name, date, data: []};
r[name + "_" + date].data.push({name,date,comment});
return r;
},{}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 基于javascript中的多个键对数据进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55143307/

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