0

I'm currently developing a small application to register devices on a database.

For the frontend I decided to use VueJS.

This is how I am initializing the app:

//App Vuejs
var app = new Vue({
    el: '#register-device-app',
    data: {
        currentDevice: {
           internalid: '',
           imei: '',
           tel: ''
        },
        devices[]
    },
    ....
});

I'm binding the internalid, imei, tel and some other fields to a form and the data is stored on app.currentDevice which is great.

Now I would like to push the app.currentDevice to the array devices[] so I can add more.

The problem I am facing is that if I use app.devices.push(app.currentDevice), as soon as I modify the content of the currentDevice, since the object in the array is the same, the data in the array will also change, which I don't want. I want to have the devices array to be like a local mini-database that will only hold the information until I send it to the database.

The solution I found was to use jQuery extend() app.devices.push(jQuery.extend({}, app.currentDevice)); but I don't think this is the best solution and I'd like to know if there are some other easy and more elegant ways to do this.

Can someone leave a suggestion?

Thank you so much!

2 Answers 2

1

I'm going to assume you're working with an Object with no functions and just properties which you want to deep copy into a new object. If you're certain you're working with JSON-like data, you could use JSON.parse and JSON.stringify, which should be a speedy way to deep clone an object like that:

var device = JSON.parse(JSON.stringify(app.currentDevice));

This newly created device variable will be independent of the original variable and you can modify app.currentDevice without the other variable updating with it.

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

Comments

1

In your function that handles the push from currentDevice to devices, you need to CLONE the current device object, not push it as is, as that will simply create a reference from the currentDevices to the array. If you are using ES6, you can use Object.assign(), thus:

hander () {
  // copy this.current device props to new empty object
  const device = Object.assign({}, this.currentDevice)
  // push this new object
  devices.push(device)
  // do whatever you need to do to reset currentDevice ...
}

If you aren't using ES6, you can use underscore or lodash equivalent methods, I think it's _.extend() if I'm not mistaken

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.