如何将数据推送到嵌套对象 [英] How to push data to a nested Object

查看:50
本文介绍了如何将数据推送到嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将另一个元素从下面的对象推入 variables 属性?

How can I push another element to the variables property from the below object?

  var request = {
    "name": "Name",
    "id": 3,
    "rules":[
      {
        "name": "Rule name",
        "tags": [
          {
            "tagId": 1,
            "variables":[
              {
                "variable": "var1",
                "matchType": "Regex",
                "value": ".*"
              },
              {
                "variable": "var2",
                "matchType": "Regex",
                "value": ".*"
              }
            ],
            "condition": false,
          },
          {
            "tagId": 1,
            "condition": false,
          }
        ],
        "ruleSetId": 3,
      }
    ]
  }

例如,我需要将 {"variable":"var3","matchType":"Regex","value":.*"} 添加到变量来自 request 对象的属性...我该怎么做?

For exaple, I need to add {"variable": "var3", "matchType": "Regex", "value": ".*"} to the variables property from request Object...how can I do this?

for(i=0;i<duplicates.length; i++) {
  var request = {
    "name": duplicates[i].scope,
    "id": 3,
    "rules":[
      {
        "name": duplicates[i].scope + " " + "OP SDR Sync",
        "tags": [
          {
            "tagId": 1,
            "variables":[
              {
              }
            ],
            "condition": false,
          },
          {
            "tagId": 1,
            "condition": false,
          }
        ],
        "ruleSetId": 3,
      }
    ]
  }

  request.rules[0].tags[0].variables[0].push({
    "variable":"var3",
    "matchType": "Regex",
    "value": ".*"
  });
}

推荐答案

您必须在对象中正确导航":

You have to "navigate" properly in your object:

request.rules[0].tags[0].variables.push({
  "variable":"var3",
  "matchType": "Regex",
  "value": ".*"
})

request ['variables'] 只会尝试在 request 对象的根目录中找到 variables 键.只是没有定义此键,而是将其嵌套在对象/数组结构中.

request['variables'] will just try to find the variables key in root of the request object. This key is simply not defined but is nested in your object/array structure.

这篇关于如何将数据推送到嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆