Pavel Valeriu Pavel Valeriu - 5 months ago 6
Javascript Question

How can I append a new property to JS object

Here is my JS object:

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


How can I add a new property
"value": "some value"
to the
variables
objects? For example, after I add this property, the object should look like this:

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


I tried the following but it adds me an additional object that only contains
{"value": "some value"}
:

request.rules[0].tags[0].variables.push({
"value": "some value"
});

Answer
request.rules[0].tags[0].variables[0].value = "some value";

Or if you want to append this new property in all variables:

var target = 'value';

for (var i = 0; i < request.rules[0].tags[0].variables.length; i++) { 
  if (request.rules[0].tags[0].variables[i][target]) { 
    break;
  }
}

request.rules[0].tags[0].variables[i][target] = "some value";
Comments