gpt4 book ai didi

javascript - 创建不同的数据集数组

转载 作者:行者123 更新时间:2023-11-30 15:05:02 25 4
gpt4 key购买 nike

我正在尝试根据月值创建不同的数据集。例如。 6 月是一个数据集,7 月是另一个数据集。但在我的代码中,所有月份的值都被合并并创建为一个数据集。

谁能帮我动态创建不同的数据集,那将非常有帮助。我附上了我用我的数据对象试过的 fiddle

JSFIDDLE

var obj = [{
date: "2017-06-01",
reqC: "129963",
month: "JUNE",
resC: "80522"
}, {
date: "2017-06-05",
reqC: "261162",
month: "JUNE",
resC: "83743"
},{
date: "2017-07-03",
reqC: "438860",
month: "JULY",
resC: "166107"
}]
var maindataset = [];
var dataset = [];
["reqC", "resC"].forEach((series) => {
dataset.push({
seriesname: series,
data: obj.map((el) => {
return el[series]
})
})

});
maindataset.push({
dataset: dataset
});
alert(JSON.stringify(maindataset));

// Expected Output

{
"dataset": [
{
"dataset": [ //June
{
"seriesname": "Req",
"data": [
{
"value": "129963"
},
{
"value": "261162"
}
]
},
{
"seriesname": "Res",
"data": [
{
"value": "80522"
},
{
"value": "83743"
}
]
}
]
},
{
"dataset": [ //July
{
"seriesname": "Req",
"data": [
{
"value": "438860"
}
]
},
{
"seriesname": "Res",
"data": [
{
"value": "166107"
}
]
}
]
}
]
}

最佳答案

您可以使用嵌套哈希表并稍后迭代所需部分的键。

var data = [{ date: "2017-06-01", reqC: "129963", month: "JUNE", resC: "80522" }, { date: "2017-06-05", reqC: "261162", month: "JUNE", resC: "83743" }, { date: "2017-07-03", reqC: "438860", month: "JULY", resC: "166107" }],
result = { dataset: [] },
parts = { reqC: 'Req', resC: 'Res' },
hash = { _: result.dataset };

data.forEach(function (a) {
var temp = hash;
if (!temp[a.month]) {
temp[a.month] = { _: [] };
temp._.push({ dataset: temp[a.month]._ });
}
temp = temp[a.month];
Object.keys(parts).forEach(function (k) {
if (!temp[k]) {
temp[k] = { _: [] };
temp._.push({ seriesname: parts[k], data: temp[k]._ });
}
temp[k]._.push({ value: a[k] });
});
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 创建不同的数据集数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45914481/

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