Faiyet
Faiyet

Reputation: 5471

Append new properties to existing JSON object

I have the following json

{"groupOp":"AND","rules":[{"field":"company","op":"cn","data":"School"}]}

I want to inject new properties into every item in the rules array to get something like this.

{"groupOp":"AND","rules":[{"field":"company","op":"cn","data":"School", "dataType": "Organization", "dataProperty": "name"}]}

The plan is to loop through the array called rules and dynamically add the correct values using the following.

var filters = $.parseJSON(postData.filters); 
var rules = filters.rules;
for (i = 0; i < rules.length; i++) { 
  rules[i]
}

I have access to rules at index "i". I tried rules[0].push({dataType: "Organization"}); please help.

Upvotes: 1

Views: 2961

Answers (2)

Viele
Viele

Reputation: 2336

Is this what you are looking for?

var filters = $.parseJSON(postData.filters); 
var rules = filters.rules;
for (i = 0; i < rules.length; i++) { 
  rules[i].dataType = "Organization";
}

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359986

rules[i] is an object, not an array, so there is no push method to call. Use property assignment.

// ...
rules[i].dataType = "Organization";
// ...

Upvotes: 4

Related Questions