Matias Celiz
Matias Celiz

Reputation: 322

Add a property into a JSON object JS

I have this JSON:

{
"id": 10,
"name": "Color test2",
"seed_id": 1,
"season_id": 2,
"description": null,
"work_schedule_type_id": 2,
"color": "#00A946",
"active": false,
"starred": true,
"phases": [{
    "id": 2,
    "name": "Phase2",
    "work_schedule_type_id": 2,
    "phase_color": "#343434",
    "phase_order_of_operations": 1,
    "description": "TEST PHASE TYPE2",
    "isExpanded": false,
    "$$hashKey": "object:1387"
}]

}

I need add a property tasks for each phase in phases. How I can do this?

Upvotes: 0

Views: 134

Answers (3)

Karl-Henry Martinsson
Karl-Henry Martinsson

Reputation: 2795

Assuming your JSON object is named json, the code would look something like this:

for (phase of json.phases) {
    phase.task = "somevalue";
}

Upvotes: 0

Ele
Ele

Reputation: 33726

This approach adds the tasks from an Array.

var obj = {
  "id": 10,
  "name": "Color test2",
  "seed_id": 1,
  "season_id": 2,
  "description": null,
  "work_schedule_type_id": 2,
  "color": "#00A946",
  "active": false,
  "starred": true,
  "phases": [{
    "id": 2,
    "name": "Phase2",
    "work_schedule_type_id": 2,
    "phase_color": "#343434",
    "phase_order_of_operations": 1,
    "description": "TEST PHASE TYPE2",
    "isExpanded": false,
    "$$hashKey": "object:1387"
  }]
}

var tasks = ["Task1", "Task2"];
obj.phases.forEach(p => p.tasks = tasks);

console.log(obj.phases);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

rijin
rijin

Reputation: 1759

angular.forEach(obj.phases, function(item) { item.tasks = your_val } );

Upvotes: 2

Related Questions