0

I was coding in javascript and I needed to create an object with multiple sub-objects that would hold the same named variables. When I tried to push values to one sub-object, the others also would also get it. I simulated the behavior in the browser console as following:

object = {};
numbers = [0,1]; 
letters = ["a","b"]
fruits = ["peach", "pineapple"]


object.subObject1 = { numbers , letters , fruits };
object.subObject2 = { numbers , letters , fruits };

object.subObject1.numbers.push(3);
console.log(object.subObject2.numbers);

OUTPUT: [0, 1, 3]

So, when I push into the array1 sub-object. It also goes to the array2 sub-object, because apparently the numbers array is passed by reference. My question is, how can I do this so that they will keep the sub-object array property name ('numbers') but pass the array by value?

1
  • 2
    this(object.subObject1 = { numbers , letters , fruits }) is invliad it will not work in some browsers Commented Aug 14, 2015 at 5:18

1 Answer 1

2

Try this code.

object.subObject1 = { numbers: numbers.slice(), letters: letters.slice(), fruits: fruits.slice() };
object.subObject2 = {  numbers: numbers.slice(), letters: letters.slice(), fruits: fruits.slice() };

object.subObject1.numbers.push(3);
console.log(object.subObject2.numbers);

slice apparently invokes that a new array is created for the objects based from the former array, not just passed as the reference.

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

2 Comments

but declaration use this object.subObject1 = { numbers: numbers,.. }
cool, that's excatly what I was missing, the "name: value" notation

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.