0

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?

Matias Celiz
  • 322
  • 3
  • 11
  • What information will have the task? – juan garcia Feb 16 '18 at 13:20
  • Possible duplicate of https://stackoverflow.com/questions/736590/add-new-attribute-element-to-json-object-using-javascript – Tanmay Feb 16 '18 at 13:21
  • 1
    Possible duplicate of [Is it possible to add dynamically named properties to JavaScript object?](https://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object) – Jared Smith Feb 16 '18 at 13:22

3 Answers3

2
angular.forEach(obj.phases, function(item) { item.tasks = your_val } );
rijin
  • 1,709
  • 12
  • 21
1

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; }
Ele
  • 33,468
  • 7
  • 37
  • 75
0

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

for (phase of json.phases) {
    phase.task = "somevalue";
}
Karl-Henry Martinsson
  • 2,770
  • 15
  • 25