How to push data to a nested Object

后端 未结 5 759
醉梦人生
醉梦人生 2021-01-17 02:48

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

  var request = {
    \"name\": \"Name\",
    \"id\": 3,
    \"r         


        
相关标签:
5条回答
  • 2021-01-17 03:28

    You have to "navigate" properly in your object:

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

    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.

    0 讨论(0)
  • 2021-01-17 03:36

    Try like this:

    object = {"variable": "var3", "matchType": "Regex", "value": ".*"};
    request.rules[0].tags[0].variables.push(object);
    
    0 讨论(0)
  • 2021-01-17 03:43

    dot operator(.) can be used to get the value of a particular object property.

    square brackets ([]) can be used to access an element of an array.

    Now the answer to your question:

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

    here, [0] specifies the first element of your array.

    0 讨论(0)
  • 2021-01-17 03:50

    Try:

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

    variables is into tags, and tags is into rules.

    I edited the answer

    0 讨论(0)
  • 2021-01-17 03:53
    request.rules[0].tags.variables[0].push({
      "variable":"var3",
      "matchType": "Regex",
      "value": ".*"
    });
    

    You have to navigate in your array. Replace the 0 inside the [] to select the item from the array. (0 is first entry, 1 is second entry etc).

    0 讨论(0)
提交回复
热议问题