在Javascript中动态地将键值添加到嵌套对象

时间:2017-07-05 12:01:13

标签: javascript json object

这可能与this重复,但在那里没有得到适当的解决方案。我的对象如下,

var replyDataObj = {

                  "department": {
                    "name": getCache("departmentName")
                  },
                  "subject": replyEmailSubject,  
                  "payload": {
                    "email": {
                      "contents": {
                        "content": [
                          {
                            "type": "html",
                            "value": replyEmailContent
                          }   
                        ]
                      },
                      "emailAddresses": {
                        "from": fromEmailId,
                        "to": {
                          "address": [
                            toEmailId
                          ]
                        }        
                      }
                    }
                  }  
            }

我想根据cc字段是否存在,动态地将以下键值添加到'emailAddresses'键中,

"cc": {
         "address": [
           ccEmailId
          ]
      }  

所以它看起来像,

var replyDataObj = {

              "department": {
                "name": getCache("departmentName")
              },
              "subject": replyEmailSubject,  
              "payload": {
                "email": {
                  "contents": {
                    "content": [
                      {
                        "type": "html",
                        "value": replyEmailContent
                      }   
                    ]
                  },
                  "emailAddresses": {
                    "from": fromEmailId,
                    "to": {
                      "address": [
                        toEmailId
                      ],
                    "cc": {
                      "address": [
                         ccEmailId
                        ]
                      } 
                    }        
                  }
                }
              }  
        }

我尝试使用object [key]添加它,如下所示,object.key但没有运气

replyDataObj[payload][emailAddresses][cc]={
     "address": [
       ccEmailId
      ]
  } 

我尝试了多种方法并进行了大量搜索,但没有得到解决方案。在这方面的任何帮助将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:4)

将字符串放在[]

replyDataObj['payload']['emailAddresses']['cc']={
     "address": [
       ccEmailId
      ]
  } 

答案 1 :(得分:0)

@ K.Kirsz回答说,我在[](引号)中缺少字符串。还添加了缺少'email'键来解决我的问题。

replyDataObj['payload']['email']['emailAddresses']['cc']={
 "address": [
   ccEmailId
  ]

}