skr07
skr07

Reputation: 725

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
            }

Upvotes: 0

Views: 42

Answers (1)

user2085143
user2085143

Reputation: 4232

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));

Upvotes: 1

Related Questions