Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuejs copying data object and removing property will remove the property from original object as well

I have a data object in vue that looks like this

rows[
0 {
  title: "my title",
  post: "my post text",
  public: false,
  info: "some info"
},
1 {
 title: "my title",
  post: "my post text"
  public: true,
  info: "some info"
},
2 {
 title: "my title",
  post: "my post text"
  public: false,
  info: "some info"
}
]

I then copy that object and remove certain properties if needed before posting the object to my backend like this:

var postData = this.rows;
      postData.forEach(function(o) {

        if (o.public === true) {
          delete o.info;
        }
      });

      var uploadData = {};
      uploadData.blogpost = postData;
      axios({
          method: 'post',
          url: myUrl,
          responseType: 'json',
          data: uploadData
        })

The problem is that delete o.info; will also remove the property from my vm root data, and I dont understand why since I created a new varible/copied the root data into that one. So how can I remove certain object properties from my data before posting it without altering my root data vm in vue ?

like image 620
user2722667 Avatar asked Jan 21 '18 04:01

user2722667


People also ask

How do I remove a property from Vue?

To delete property from a data object with Vue. js, we can use the this. $delete method.

How does Vue reactivity work?

Vue's reactivity system works by deeply converting plain JavaScript objects into reactive proxies. The deep conversion can be unnecessary or sometimes unwanted when integrating with external state management systems (e.g. if an external solution also uses Proxies).

Are Vue methods reactive?

Vue comes with the reactive method, which is used to create a reactive state in JavaScript or Vue. Basically, the reactive method is just a function that creates a proxy and wraps it around provided data objects, ultimately turning it into a proxied object.

What is watch property in VUE JS?

The Vue. js Watcher or watch property allows the developers to listen to the component data and run whenever they change a particular property. The watcher or watch property is a unique Vue. js feature that lets you keep an eye on one property of the component state and run a function when that property value changes.


1 Answers

You need to take a copy of your data by cloning it. There are various ways of cloning the data, I would recommend using lodash's function, cloneDeep

postDataCopy = _.cloneDeep(postData)

Then you can modify postDataCopy as you like without modifying the original.

like image 131
Mikkel Avatar answered Oct 14 '22 13:10

Mikkel