[Vuejs]-How to delete data using Vue js?

0👍

From what I’ve understood from your code,

this should work for removing jobPost from jobPosts

this.jobPosts = this.jobPosts.filter(obj => {
    return obj.id != jobPost.id;
});

I don’t know what you’re expecting this to do, but it won’t do anything useful and will either error or return false for everything.

this.jobPosts = Object.keys(this.jobPosts).filter(obj => {
    return obj.id != jobPost.id;
});

filter exists on array types, so I would check where it’s getting set and make sure it’s an array.

I’ve included a small snippet in case it’s any help.

Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
  el: "#app",
  data: () => {
    return {
      jobPosts: [],
      deleteJobId: 1
    };
  },
  methods: {
    getJobPosts() {
      this.jobPosts = [{
        id: 1
      }, {
        id: 2
      }, {
        id: 3
      }, {
        id: 4
      }, {
        id: 5
      }];

    },
    deleteJob() {
      if (!this.deleteJobId)
        return;

      this.jobPosts = this.jobPosts.filter(x => x.id !== this.deleteJobId);
    }

  }



});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button type="button" @click="getJobPosts">Get Jobs</button>

  <div>
    <button type="button" @click="deleteJob">Delete Job #</button>
    <input type="number" v-model.number="deleteJobId" />

  </div>
  <ul>
    <li v-for="jobPost in jobPosts">
      Job Post #{{jobPost.id}}
    </li>
  </ul>
</div>

0👍

You have already answered your own question:

in my data() object, I have this jobPosts: [], but in the console it says Object

As for your second question:

I don’t know how to return the data as an array

There are similiar topics here on SO.
I am not familiar with Laravel but assuming you have an eloquent model with JobPost in your index-function according to the docs you should use the .toArray-method:

$jobPosts = JobPost::all()->where('user_id', Auth::user()->id).toArray();

When working with plain collections the values method should do the trick of returning an array instead of an object:

$collection = collect([
  10 => ['product' => 'Desk', 'price' => 200],
  11 => ['product' => 'Desk', 'price' => 200]
]);

$values = $collection->values();

$values->all();

UPDATE

I just realized that your result is just a stringified JSON object that needs to be converted into an array. Just parse it before processing (take out the JSON.parse(…) if you are already taking care of it in your service), return the object properties as an array and you are good to go:)

this.jobPosts = Object.values(JSON.parse(this.jobPosts)).filter(obj => {
  return obj.id != jobPost.id;
});

Leave a comment