gpt4 book ai didi

javascript - 在 Javascript 中对嵌套数组进行分组

转载 作者:行者123 更新时间:2023-11-29 16:05:12 27 4
gpt4 key购买 nike

我有一组用于可视化的数据,格式如下

var Dataset1 =  [
{
"commentBy" : "saurabh",
"comment" : "Testing",
"datestamp" : "07/07/2017",
"weekcount" : 1
},

{
"commentBy" : "raman",
"comment" : "Planning",
"datestamp" : "07/07/2017",
"weekcount" : 1
},
{
"commentBy" : "Execution",
"comment" : "Alfa Beta",
"datestamp" : "07/07/2017",
"weekcount" : 2
},
{
"commentBy" : "Execution",
"comment" : "Zseta Gama",
"datestamp" : "07/07/2017",
"weekcount" : 2
}
]

//although i have tried writing this function but this is not giving me the desired result.


var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {

(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
var groubedByTeam=groupBy(Dataset1, 'weekcount')
console.log(groubedByTeam);

我想按周计数对数据集进行分组,这样所需的结果应该是这样的。

    [
{ "weekcount" : 1
"grouped" : [
{ "commentBy" : "saurabh",
"comment" : "Testing",
"datestamp" : "07/07/2017"
},
{
"commentBy" : "raman",
"comment" : "Planning",
"datestamp" : "07/07/2017"
}
]
}, {
"weekcount" : 2
"grouped" : [
{
"commentBy" : "Execution",
"comment" : "Alfa Beta",
"datestamp" : "07/07/2017",

},
{
"commentBy" : "Execution",
"comment" : "Zseta Gama",
"datestamp" : "07/07/2017",

}
]
}
]

最佳答案

const formatted = [];

Dataset1.forEach((data) => {
const { weekcount, comment, commentBy, datestamp } = data;
let obj = formatted.find((item) => item.weekcount === weekcount);

if (!obj) {
formatted.push({
weekcount,
grouped: [{
comment,
commentBy,
datestamp
}]
})
} else {
obj.grouped.push({
comment,
commentBy,
datestamp
});
}
});

const Dataset1 = [{
"commentBy": "saurabh",
"comment": "Testing",
"datestamp": "07/07/2017",
"weekcount": 1
}, {
"commentBy": "raman",
"comment": "Planning",
"datestamp": "07/07/2017",
"weekcount": 1
}, {
"commentBy": "Execution",
"comment": "Alfa Beta",
"datestamp": "07/07/2017",
"weekcount": 2
}, {
"commentBy": "Execution",
"comment": "Zseta Gama",
"datestamp": "07/07/2017",
"weekcount": 2
}];

const formatted = [];

Dataset1.forEach((data) => {
const { weekcount, comment, commentBy, datestamp } = data;
let obj = formatted.find((item) => item.weekcount === weekcount);

if (!obj) {
formatted.push({
weekcount,
grouped: [{
comment,
commentBy,
datestamp
}]
})
} else {
obj.grouped.push({
comment,
commentBy,
datestamp
});
}
});

console.log(formatted);

关于javascript - 在 Javascript 中对嵌套数组进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45006501/

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