user4324324 user4324324 - 1 month ago 11
JSON Question

creating different dataset array

I am trying to create different dataset based on month value. For eg. for June month one dataset and for July another dataset. But in my code, all the month values are getting combined and created as one dataset.

It will be really helpful who can help me in creating different dataset dynamically. I have attached the fiddle which I tried with my data object

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"
}
]
}
]
}
]
}

Answer Source

You could use a nested hash table and iterate later the keys for the wanted parts.

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; }