简体   繁体   English

如何将对象推入Angular.js中的数组

[英]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. 实际上,可以向书籍添加更多对象,也可以向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? 我的问题是如何向书籍添加更多对象,以及向allBooks添加更多数组?

Actually instead of adding properties dynamically you should rethink the structure of the allBooks object you're trying to create. 实际上,与其动态添加属性,不如重新考虑要创建的allBooks对象的结构。 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. 这将使您可以将书籍集合推入allBooks集合。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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