satheesh satheesh - 18 days ago 5
AngularJS Question

angularjs append value into inside array

I am having array in below format. i am having issue to append the value inside each chapter array. i need to add field like 'checked:true'. I need to get the data in same format. Expectation is, need same format with added one field inside chapter array.

{
"Books": [
{
"label":"Book1",
"data": [
{
"bookId": 3561,
"bookName": "AJ200",
"chapters": [
{
"id": 3926,
"name": "red"
},
{
"id": 3927,
"name": "yellow"
},
{
"id": 3928,
"name": "black"
}
]
}
]
},
{
"label":"Book2",
"data":[
{
"bookId": 3561,
"bookName": "AJ200",
"chapters": [
{
"id": 3564,
"name": "blue"
},
{
"id": 3565,
"name": "orange"
}
]
}
]
}
]
}


after adding field chapters array looks like as below,

"chapters": [
{
"id": 3564,
"name": "blue",
"checked":true
},
{
"id": 3565,
"name": "orange"
"checked":true
}

Answer

This is a little verbose but works all the same!

var myObject = 
{ 
  "Books": [
    {
      "label":"Book1",
      "data": [
        {
          "bookId": 3561,
          "bookName": "AJ200",
          "chapters": [
            {
              "id": 3926,
              "name": "red"
            },
            {
              "id": 3927,
              "name": "yellow"
            },
            {
              "id": 3928,
              "name": "black"
            }
          ]
        }
      ]
    },
    {
      "label":"Book2",
      "data":[
        {
          "bookId": 3561,
          "bookName": "AJ200",
          "chapters": [
            {
              "id": 3564,
              "name": "blue"
            },
            {
              "id": 3565,
              "name": "orange"
            }
          ]
        }
      ]
    }
  ]
}

var books = myObject.Books;


for(var i=0; i<books.length; i++) {

  var bookData = books[i].data;

  for(var j=0;j<bookData.length;j++) {

    var chapters = bookData[j].chapters;

    for(var k=0;k<chapters.length;k++) {

      chapters[k].checked = true;

    }

  }

}

console.log(JSON.stringify(books));