1

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?

3
  • 1
    can you provide fiddle ? Commented Nov 15, 2015 at 9:59
  • you problem: you alwasy add same object Commented Nov 15, 2015 at 11:34
  • what should do addDataToArray? can you provide sample input and sample output for this? Commented Nov 15, 2015 at 11:38

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.