I have the following object
{
"timetable": {
"MONDAY": {
"start-end0": {},
"start-end1": {},
"start-end2": {},
"start-end3": {},
"start-end4": {}
}
}
i need to add "start-end5"
to MONDAY
. I tried to use dot operator to monday like timetable.monday.start-end5={}
it says monday undefined
I have the following object
{
"timetable": {
"MONDAY": {
"start-end0": {},
"start-end1": {},
"start-end2": {},
"start-end3": {},
"start-end4": {}
}
}
i need to add "start-end5"
to MONDAY
. I tried to use dot operator to monday like timetable.monday.start-end5={}
it says monday undefined
4 Answers
Reset to default 8monday
is notMONDAY
- Since
start-end4
is not a valid identifier,obj.timetable.MONDAY.start-end5 = {}
will not pile; you need to use the bracket syntax.
Thus,
obj.timetable.MONDAY["start-end5"] = {};
Variable name should be followed this restrictions
- Blanks & Commas are not allowed.
- No Special Symbols other than underscore(_) are allowed.
- First Character should be alphabet or Underscore.
Try like this
var time = {
"timetable": {
"MONDAY": {
"start-end0": {},
"start-end1": {},
"start-end2": {},
"start-end3": {},
"start-end4": {}
}
}
}
time.timetable.MONDAY["start-end5"] = {}
DEMO
Addtion:
how can i add dynamically start-end5 start-end6... to my map??Is that possible?
Ans
Add a loop and concat string according to value.
Like this
var time = {
"timetable": {
"MONDAY": {
"start-end0": {},
"start-end1": {},
"start-end2": {},
"start-end3": {},
"start-end4": {}
}
}
}
for(var i=0;i<5;i++) // set the limit of loop according to your need
time.timetable.MONDAY["start-end"+i] = {}
DEMO
You need to use the [""]
notation here, as your key name is not camelCase or other valid object key naming
a.timetable.MONDAY["start-end5"] = {};
One more pletely viable (and very readable) syntax I'd like to add, just for fun:
time["timetable"]["MONDAY"]["start-end5"] = {};