3

Sorry if its a very easy question, i tried following some answers in here but i couldnt..

I want to add a NEW object to an array, based on the first one

The way i find that works is this one:

    new Vue({
    el: "#app",
    data: {
       name: '',  //name isnt inside and object
     //failedExample: {name: ''}
        array: []
    },
    methods: {
        add(){
            this.array.push({name: this.name}) // i push a key:value
          //this.array.push(failedExample) // what i wished to do
        }
    }
});

https://jsfiddle.net/myrgato/6mvx0y1a/

I understand that by using the commented array.push, i would just be adding the same reference to the object over and over, so when i change the value of failedExample.name, it will change in all positions of the array. Is there a way that this doesnt happens? Like, i add the first object, then the next one as a NEW instead of a reference?

1
  • Can you give us an example of your desired outcome? Commented Jul 20, 2017 at 15:11

1 Answer 1

6

It should work as you wanted to do with your 'failedExample'. The only wrong thing I see is that you forget the this keyword when you're pushing into array.

So try this one:

 new Vue({
    el: "#app",
    data: {
      failedExample: { name: 'test'},
      array: []
    },
    methods: {
        add(){
          this.array.push(this.failedExample);
          console.log(this.array);
        }
    }
});

Update: If you want to add a new object each time, then try to clone it so you will not have refference problems:

this.array.push(Object.assign({}, this.failedExample));
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thank you very much!

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.