Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js - Don't bind an object when 'copying it' to another data attribute

I have an object coming from my API and when loading a modal I need to 'duplicate' the object to another.

This works:

this.servicesForm.services = this.team.services;

// New object                // API object

The issue now is that I DON'T want the team.services object to be bound to and update when I update the servicesForm.services object.

How do I do that?

like image 795
Lovelock Avatar asked Jul 05 '17 11:07

Lovelock


2 Answers

Quickly found my answer:

this.servicesForm.services = JSON.parse(JSON.stringify(this.team.services));
like image 51
Lovelock Avatar answered Oct 20 '22 22:10

Lovelock


An ES6 solution would be to use Object.assign:

this.servicesForm.services = Object.assign({}, this.team.services); 

Note that this is only a shallow copy, if you need a deep copy you would need to apply this method recursively.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

like image 22
Antony Avatar answered Oct 20 '22 22:10

Antony