[Vuejs]-How can I remove a property from an object in an array?

1๐Ÿ‘

โœ…

You can loop through the array and create another array

var vm = 
new Vue({
  el: "#app",
  data: {
    options: [
      {id:100, option:"1 - John Doe"},
      {id:200, option:"2 - Jane Doe"}
    ]
  },
  methods: {
    getNames(){
      
      let names = this.options.map(option => {
        return { 
          option: option.option
        }
      });
      
      console.log(names);
    }
  }
  
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="getNames()">TEST</button>
</div>
๐Ÿ‘คRotiken Gisa

1๐Ÿ‘

You can use map method:

var vm = 
new Vue({
  el: "#app",
  data: {
    options: [
      {id:100, option:"1 - John Doe"},
      {id:200, option:"2 - Jane Doe"}
    ]
  },
  methods: {
    getNames(){
      
      let names = this.options.map(o => o.option);
      
      console.log(names);
    }
  }
  
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="getNames()">TEST</button>
</div>

1๐Ÿ‘

This is a pure JavaScript task. It is solvable independently from VueJS or any other framework.

In general you can apply two approaches (either keep what is needed or remove what is obsolete):

  1. map: to transform each source element to the new target format; returns a new array
  2. forEach with delete: to remove the unwanted property from the original array
let options: [
  {id:100, option:"1 - John Doe"},
  {id:200, option:"2 - Jane Doe"}
];

// to get a new (simple) array of strings
let strings = options.map(o => o.option);
console.log(strings);

// to get the same array with nested objects where property was removed
options.forEach(o => delete o.id);
console.log(options);

See also:
Remove property for all objects in array

๐Ÿ‘คhc_dev

Leave a comment