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
monday
is not MONDAY
start-end4
is not a valid identifier, obj.timetable.MONDAY.start-end5 = {}
will not compile; you need to use the bracket syntax. Thus,
obj.timetable.MONDAY["start-end5"] = {};
Variable name should be followed this restrictions
Try like this
var time = {
"timetable": {
"MONDAY": {
"start-end0": {},
"start-end1": {},
"start-end2": {},
"start-end3": {},
"start-end4": {}
}
}
}
time.timetable.MONDAY["start-end5"] = {}
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] = {}
您需要在此处使用[""]
表示法,因为您的键名不是camelCase或其他有效的对象键名
a.timetable.MONDAY["start-end5"] = {};
我想添加一种更可行(且易读)的语法,只是为了好玩:
time["timetable"]["MONDAY"]["start-end5"] = {};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.