Search code examples
arraysjsonvue.jsfilterv-for

Dont know how to Filter an array from API Plattform (Symfony) in Vuejs (script setup)


in my little local vuejs-project (script setup) i'm receiving dummy-data (getTutorials) from my api (symfony, api plattform). The dummy-data have a value "true" or "false" from Database-Column "published". Dummy-Data in Database

What i have: 2 columns:

  • Left Column: Published
  • Right Column: Unpublished

Picture from the 2 Columns

what i want:

  • v-for loop for all Data with boolean "true" in the left Column.
  • v-for loop for all Data with boolean "false" in the right Column.

what i have:

  • all data ("true" and "false") are in the left Column.
  • no data (with "false") in the right Column.

my Code:

<script setup>
import { ref } from "vue";
import TutorialDataService from "../services/TutorialDataService";

const tutorials = ref("");

const getTutorials = TutorialDataService.getAll()
  .then((response) => {
    tutorials.value = response.data["hydra:member"];
    // console.log(response.data["hydra:member"]);
    console.log("---Retrieve OK---");
  })
  .catch((e) => {
    console.log(e);
  });
</script>
<template>
<div class="grid grid-cols-2 gap-4">
    <div class="bg-slate-50/10 p-3 rounded-md">Published:
        <ul class="list-disc list-inside">
            <li v-for="item in tutorials" :key="item.id">
                {{ item.title }} - <b>{{ item.published }}</b>
            </li>
        </ul>
    </div>
    <div class="bg-red-300  p-3 rounded-md text-black">Unpublished:
        <ul class="list-disc list-inside">
            <li class="text-black" v-for="item in filtered" :key="item.id">
                {{ item.title }}
            </li>
        </ul>
    </div>
</div>
</template>

what i need: Dont know how to filter this Dummy-Data with computed or a method. Can anyone help me to filter the received dummy-data, that i can make a v-for loop for the right Column?

Thank You Tom


Solution

  • You just need to filter your data when you get it from api:

    const getTutorials = TutorialDataService.getAll()
      .then((response) => {
        const data = response.data["hydra:member"]; // Saved this into local variable
        tutorials.value = data.value.filter((item) => !item.published); // Filter to get all tutorials with published = 0
        filtered.value = data.value.filter((item) => !!item.published); // Filter to get all tutorials with published = 1
        // console.log(response.data["hydra:member"]);
        console.log("---Retrieve OK---");
      })
      .catch((e) => {
        console.log(e);
      });
    
    

    Using ! and !! operators here, more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT