Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js 2: Delete property from data object

How can you delete a property/key from a Vue.js data object (i.e. associative array) like this:

var vm = new Vue({     data: {         users: {             foo : { firstName: ..., lastName: ... },             bar : { firstName: ..., lastName: ... }         }     },     methods: {         someFunction : function ()         {             // how to remove `users.foo`?         }     } }); 

Googling around, I found these two ways, but both don't work:

  • delete this.users.foo; is not updating the DOM
  • this.users.splice('foo', 1); is not working at all (probably only works on arrays, not on objects)
like image 696
Thomas Landauer Avatar asked Jul 06 '17 16:07

Thomas Landauer


People also ask

How do you remove properties from an object?

In JavaScript, there are 2 common ways to remove properties from an object. The first mutable approach is to use the delete object. property operator. The second approach, which is immutable since it doesn't modify the original object, is to invoke the object destructuring and spread syntax: const {property, ...

How do I remove a property name from an object?

The delete operator is used to remove these keys, more commonly known as object properties, one at a time. The delete operator does not directly free memory, and it differs from simply assigning the value of null or undefined to a property, in that the property itself is removed from the object.

How do I destroy Vue components?

To make a component delete itself in Vue. js, we can use the this. $destroy method. to add the close method to call this.


1 Answers

The answer is:

Vue.delete(users, 'foo'); 

It took me a while to find it, that's why I'm posting it here ;-)
https://github.com/vuejs/vue/issues/3368#issuecomment-236642919

like image 74
Thomas Landauer Avatar answered Oct 07 '22 06:10

Thomas Landauer