简体   繁体   中英

How push object onto array of array in Angularjs

i want to create a object such as this

$scope.allBooks = {
                books:[
                         {
                          name:"",
                          id:""
                         } 
                          {
                          name:"",
                          id:""
                         }
                        // can be add another object
                       ]
                  books:[
                         {
                          name:"",
                          id:""
                         } 
                          {
                          name:"",
                          id:""
                         }
                       ]

             }

in fact be able to add more object to books and also add more books to allBooks. my solution is this

  $scope.allBooks = {};
  $scope.allBooks.books= [];
  var b= {
    name:"",
    id:""
  };
  $scope.allBooks.books.push(b);

my problem is how to add more object to books and also add more array to allBooks?

Actually instead of adding properties dynamically you should rethink the structure of the allBooks object you're trying to create. The way I understand it, is that you have a collection of books belonging together, which in their turn belong to another collection. In other words you have an array of arrays.

That would turn your object into something like the following:

$scope.allBooks =  [
     { id: 0,
       name: 'Harry Potter Collection',
       books: [{
                 id: 0,
                 name: 'Goblet of Fire',
                 ISBN-13: '1212245'
               },{},...] //here are the books that belong to this collection
     },
     { id: 1,
       name: 'Lord Of The Rings Collection',
       books: [{},...] //LOTR books
 ]

This will allow you to push a collection of books to your allBooks collection.

var newCollection = {
        id:2,
        name: 'AnotherCollection',
        books: []
};

var newBook = {
        id: 1354,
        name: 'Eloquent Javascript 2',
        ISBN-13: 978-1593272821
};

newCollection.books.push(newBook) //push a new book to this collection

$scope.allBooks.push(newCollection);

There are ofcourse more solutions to your problem but I'd go with a collection of collections.

Just do what you've done already:

$scope.allBooks.books2 = [];
$scope.allBooks.books2.push(b);
$scope.allBooks.books3 = [];
$scope.allBooks.books3.push(b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM