最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Push key value pair to map object javascript - Stack Overflow

programmeradmin4浏览0评论

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

Share Improve this question asked Oct 6, 2016 at 5:23 Don JoseDon Jose 1,5882 gold badges14 silver badges28 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 8
  • monday is not MONDAY
  • 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"] = {};
发布评论

评论列表(0)

  1. 暂无评论