I am new in JavaScript and programming. I get data via AJAX. I want to re-generate it to get a nested object grouped by part of the data. In this case I want it grouped by year and month
Here is my data and my function:
myObj = [
{"date":'2019-06-05',"name":"abc 0"},
{"date":'2019-06-01',"name":"abc 1"},
{"date":'2019-05-25',"name":"abc 2"},
{"date":'2019-05-15',"name":"abc 3"},
{"date":'2020-06-30',"name":"abc 4"},
{"date":'2020-06-25',"name":"abc 5"},
{"date":'2020-05-28',"name":"abc 6"},
{"date":'2020-05-26',"name":"abc 7"}
];
function regenerate(data) {
var result = {
"allyears": [{}]
};
for (x = 0; x < data.length; x++) {
var year = data[x].date.slice(0, 4);
var month = data[x].date.slice(5, 7);
if (!result.allyears.months) {
result.allyears['year'] = year;
result.allyears.months = [{}];
}
if (!result.allyears.months.data) {
result.allyears.months['month'] = month;
result.allyears.months.data = [{}];
}
result.allyears.months.data[x] = data[x];
}
console.log(result);
return result;
};
regenerate(myObj);
Result I expect:
{
"allyears": [{
"year": "2019",
"months": [{
"month": "06",
"data": [{
"date": '2019-06-05',
"name": "abc 0"
},
{
"date": '2019-06-01',
"name": "abc 1"
}
]
}, {
"month": "05",
"data": [{
"date": '2019-05-25',
"name": "abc 2"
},
{
"date": '2019-05-15',
"name": "abc 3"
},
]
}]
}]
};
What am I missing in my function?
result.allyears.months = [{}];not beresult.allyears['year'].months = [{}];, or something along those lines to put your months inside your object? Also an actual outcome next to your expected outcome would be nice.[]is an empty javascript array, the"[]"string can be parsed as the JSON representation of an empty array.