Pavel Valeriu Pavel Valeriu - 5 months ago 11
JSON Question

How to push data to a nested JSON Object

How can I push another element to the

variables
property from the below JSON 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,
}
]
}


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

I tried the following but it returns
Error: Cannot find function push in object [object Object].
:

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":[
{
"variable": duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
}
],
"condition": false,
},
{
"tagId": 1,
"condition": false,
}
],
"ruleSetId": 3,
}
]
}

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

str str
Answer

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.