简体   繁体   中英

Push key value pair to map object javascript

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
  • Since 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

  • 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

您需要在此处使用[""]表示法,因为您的键名不是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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM