I've been struggling with this issue for hours now, and I just can't seem to resolve it.
Maybe you could lend me a hand here?
Here is the JavaScript object that I have:
var year_data = {
"jan": [],
"feb": [],
"mar": [],
"apr": [],
"may": [],
"jun": [],
"jul": [],
"aug": [],
"sep": [],
"oct": [],
"nov": [],
"dec": [],
};
My desired result should look something like this:
var year_data= {
jan : [
{
23 : [
{
"1" : "some text for 23",
"2" : "some text for 23_1",
"3" : "some text for 23_2"
}
],
26 : [
{
"1" : "some text for 26",
"2" : "some text for 26_1",
"3" : "some text for 26_2"
}
]
}
],
feb : [
{
17 : [
{
"1" : "some text for 17_1",
"2" : "some text for 17_2",
"3" : "some text for 17_3"
}
]
}
],
};
I need a way to generate this object dynamically.
This is what I've tried so far:
year_data.jan.push(
{19: [{1:"Some text for 19_1",
2:"Some text for 19_2"}]
}
);
After performing JSON.stringify(year_data) everything was working fine until I tried changing 19 to a variable name.
(console) Before:
{"jan":[{"19":[{"1":"Some text for 19_1","2":"Some text for 19_2"}]}],"feb":[],"mar":[],"apr":[],"may":[],"jun":[],"jul":[],"aug":[],"sep":[],"oct":[],"nov":[],"dec":[]}
Upon making the change
var current_day=19;
year_data.jan.push(
{current_day: [{1:"Some text for 19_1",
2:"Some text for 19_2"}]
}
);
I ended up with:
{"jan":[{"current_day":[{"1":"Some text for 19_1","2":"Some text for 19_2"}]}],"feb":[],"mar":[],"apr":[],"may":[],"jun":[],"jul":[],"aug":[],"sep":[],"oct":[],"nov":[],"dec":[]}
And I'm unsure of how to fix this issue.
I attempted the solution mentioned in Using a variable for a key in a JavaScript object literal
However, the outcome was:
year_data.jan[19]=[{1:"Some text for 19_1", 2:"Some text for 19_2"}];
var json=JSON.stringify(year_data);
console: {"jan":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,[{"1":"Some text for 19_1","2":"Some text for 19_2"}]],"feb":[],"mar":[],"apr":[],"may":[],"jun":[],"jul":[],"aug":[],"sep":[],"oct":[],"nov":[],"dec":[]}
So, I am in need of either a workaround to achieve this
year_data.jan.push({**VARIABLE_name**: [{1:"Some text for 19_1", 2:"Some text for 19_2"}]});
or a solution to rectify this
year_data.jan[19]=[{1:"Some text for 19_1", 2:"Some text for 19_2"}];var json=JSON.stringify(year_data);
AND obtain
{"jan":[{"19":[{"1":"Some text for 19_1","2":"Some text for 19_2"}]}],"feb":[],"mar":[],"apr":[],"may":[],"jun":[],"jul":[],"aug":[],"sep":[],"oct":[],"nov":[],"dec":[]}
instead of
{"jan":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,[{"1":"Some text for 19_1","2":"Some text for 19_2"}]],"feb":[],"mar":[],"apr":[],"may":[],"jun":[],"jul":[],"aug":[],"sep":[],"oct":[],"nov":[],"dec":[]}
Your assistance would be greatly appreciated!