"What is the syntax for pushing an object onto an array within an array in AngularJS

Looking to create an object structure like the one below:

$scope.allBooks = {
                books:[
                         {
                          name:"",
                          id:""
                         } 
                          {
                          name:"",
                          id:""
                         }
                        // additional objects can be added here
                       ]
                  books:[
                         {
                          name:"",
                          id:""
                         } 
                          {
                          name:"",
                          id:""
                         }
                       ]

             }

I want to be able to add more objects to 'books' and also add more arrays to 'allBooks'. Here is my proposed solution:

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

However, I am facing the challenge of how to add more objects to 'books' and more arrays to 'allBooks'?

Answer №1

Instead of dynamically adding properties, consider restructuring the allBooks object you are creating. It seems like you have a group of books that belong together, which in turn belong to another group. Essentially, you have an array of arrays.

This could transform your object into something like this:

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

With this structure, you can easily push a collection of books to your allBooks.

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

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

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

$scope.allBooks.push(newCollection);

There are certainly other solutions to your issue, but organizing your data as a collection of collections is a good approach.

Answer №2

Continue with the same approach you have taken before:

$scope.favoriteBooks.list = [];
$scope.favoriteBooks.list.push(b);
$scope.savedBooks.collection = [];
$scope.savedBooks.collection.push(b);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for finishing a row of images using CSS3

Here is the code snippet that I am currently working with: <div id="images" class="img"/> <img src="spiderman.png" alt=""/> <img src="superman.png" alt="" height="25%" width="25%"/> <img src="batman.png" alt="" /> </div> ...

Encountering an error in resolving symbol values statically within the Angular module

Following a helpful guide, I have created the module below: @NgModule({ // ... }) export class MatchMediaModule { private static forRootHasAlreadyBeenCalled: boolean = false; // This method ensures that the providers of the feature module ar ...

What steps can I take to incorporate additional arguments into my function?

I am currently working with NodeJS, express, and passport. However, I believe this question is specifically related to JavaScript. Within my routes file, I have the following code: app.get( '/users', login_req, user.index); So, when a get requ ...

JavaScript/jQuery Tutorial: Accessing the src attribute of images sharing a common class名

How can I extract the src values of images with the same class and display them in an empty div? For instance: <body> <img class="class1" src="http://www.mysite.com/img/image1.jpg" width="168" height="168" alt=""> <img class="class ...

Add a CSS file to the browser-sync with proxy functionality

Currently, I have a script that I utilize to proxy a live website in order to make CSS modifications. Instead of replacing the online CSS file with a local one using a rewrite, I am exploring the possibility of injecting an entirely new file below the exis ...

Should Bower and Grunt Be Installed Globally or Locally?

When it comes to installing packages globally, we typically avoid it due to the possibility of working on multiple projects simultaneously that require different versions of the same libraries. However, there seems to be conflicting information regarding t ...

Guide to deploying a node.js web application with a local MongoDB database

Seeking guidance for a crucial query. I have developed a node.js API project that is currently linked with MongoDB on localhost. However, I intend to deploy this API for my react native project and require a URL address for it. The primary issue lies in t ...

Seeking a sleeker approach to composing various components with shared functions

Currently, I have a scenario where I have identical components that display data but also need to handle state manipulation and saving. There are 5 other similar components with slight differences in their functions. I am looking for a more efficient way t ...

Tips for integrating Material UI with Gatsby site generator

I'm diving deep into React by setting up the Gatsby kit with this site generator and Material UI framework. However, I encountered an error that says: Cannot read property 'prepareStyles' of undefined at RaisedButton.render I initiall ...

javascript - audio is not working on the web

I've been trying to incorporate sound into my website using this code. Strangely, the sounds only seem to play in Adobe Dreamweaver and not in any browsers. Any advice would be greatly appreciated! :) var audio1 = new Audio('sound1.mp3'); v ...

An alternative method to confirm the checkbox selection without physically clicking on it

Currently, I'm in the process of creating a basic to-do list and have been attempting to connect the task with its corresponding checkbox. My goal is for the checkbox to automatically be checked when the task is clicked. Instead of using HTML to add ...

Do we still need to configure XSRF-TOKEN on the server even when using HttpClientXsrfModule?

Would implementing the code below in app.module be sufficient to protect against XSRF/CSRF on the client side? HttpClientXsrfModule.withOptions({ cookieName: 'XSRF-TOKEN', headerName: 'X-XSRF-TOKEN' }) Alternatively, is additional ...

Validating HTML using EJS templates set as "text/template" elements

What is the general consensus on HTML validation when utilizing a framework such as Backbone or Meteor and generating views in the client from EJS templates? An issue arises with the fact that name is not considered an official attribute for a <script& ...

Pressing Enter triggers Submit button twice

I’m currently working on a form that includes client-side JS validation using AJAX. The form is a simple contact form with three fields: name, email, and message. If you attempt to submit the form without proper validation, error message divs will appear ...

Adjusting the rotation transform by deleting and reapplying canvas is causing the chart to not display data after redrawing

I am facing a challenge with my previous issue and I am exploring different solutions. One approach I am considering is to remove the canvas element completely and then re-add it, effectively resetting all rotations on the canvas. Although this method alm ...

Type of result from a function that returns a linked promise

In my class, I have a method that returns a chained promise. The first promise's type is angular.IPromise<Foo>, and the second promise resolves with type angular.IPromise<Bar>. I am perplexed as to why the return type of doSomething is an ...

Attempting to populate getElementByID using JavaScript function from CodeBehind proves unsuccessful

When a button is clicked on a form, I need to fill in hidden elements that will be posted. The script below should set the values for these hidden fields: <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> < ...

Using an arrow function in Aurelia to read a json file

I've been exploring Aurelia and delved into tutorials on PluralSight and Egghead.io, but I'm still struggling to resolve my current issue. In a JSON file named bob.json, there is a collection of objects related to Bob. Each object in the collect ...

You need to double click to successfully update the array in Vue/Vuex

Recently, I delved into Vue/Vuex and find myself at a loss with my current code. The method I trigger on click is as follows: Export (item) { this.exportObj = { start: this.dates[0], end: this.dates[1], userid: item.id, }; this.getAllByF ...

What is the process for incorporating a custom attribute into an element with Vue directives?

One of the challenges I'm facing is dealing with a custom attribute called my-custom-attribute. This attribute contains the ID for the element that needs to have the attribute added or removed based on a boolean value. Although I've implemented ...