Skip to content Skip to sidebar Skip to footer

Dynamically Add Array Elements To Json Object

I'm creating a JSON object from an array and I want to dynamically push data to this JSON object based on the values from array. See my code for a better understanding of my proble

Solution 1:

First of all, you dont need to parse request, you already create an object, parse only when you get JSON as string, like:

var json='{"a":"1", "b":"2"}';
var x =JSON.parse(json);

Next, you have any property of object wrapped in arrays. To correctly work with it you should write:

request.rules[0].tags[0].variables.push({
  "variable":duplicates[i].variable[j],
  "matchType": "Regex",
  "value": duplicates[i].scopeDef
})

If you want to use your code snippet, you need some changes in request:

var request = {
"name": duplicates[i].scope,
"id": 3,
"variables":[
   {
   "variable": duplicates[i].variable[j],
   "matchType": "Regex",
   "value": duplicates[i].scopeDef
   }
           ],
"rules":[
  {
    "name": duplicates[i].scope + " " + "OP SDR Sync",
    "tags": [
      {
        "tagId": 1,
        "condition": false,
      },
      {
        "tagId": 1,
        "condition": false,
      }
    ],
    "ruleSetId": 3,
  }
]
}
}

To understand JSON remember basic rule: read JSON backward. It means:

  • property
  • object.property
  • arrayOfObfects['id'].object.property
  • mainObject.arrayOfObfects['id'].object.property

and so on. Good luck!

Post a Comment for "Dynamically Add Array Elements To Json Object"