Hadi
Hadi

Reputation: 17289

How insert data to array that is in another array

I have array of array and i want to add data to inner array in javascript. Suppose my code is the following:

 self.basketsArray = [];
    self.newCollection = {
        books: []
    };
    self.basketsArray.push(self.newCollection);

  function addNewCollection(){
      self.basketsArray.push(self.newCollection);
  }
  function addDataToArray(index,index2){
     self.basketsArray[index].books.splice(index2, 1, data);
  } 

In fact, when I want to add data to the inner array it adds to first inner array. What is my problem?

Upvotes: 1

Views: 68

Answers (1)

devside
devside

Reputation: 2217

In javascript, you pass Objects and Functions by reference, others are just passed by value. You can either directly pass a new object or clone it.

// Directly push a new object: 
self.basketsArray.push({books: []}); 

// Clone it, using Angular
self.basketsArray.push(angular.copy({}, self.newCollection);); 

// Clone it, using Lodash
self.basketsArray.push(_.clone(self.newCollection)); 

Be aware that the libraries often propose shallow or deep cloning methods.

Upvotes: 1

Related Questions