LDUBBS
LDUBBS

Reputation: 603

How to hide Duplicates from inner array in Vuejs

I'm trying to delete duplicate keys from a nested array in vuejs, and remove them from the DOM

<div class="container" v-for="shops in malls">
  <div class="container" v-for="shop in shops.section">
  <div class="detail-report-item" v-for="detail in shop.shop" :key="detail.id" :id="detail.id">
    <span> {{ detail.name }} </span>
    <span> {{ detail.date }} </span>
</div>
</div>
</div>

My data is gotten from a Laravel api via axios. P.S this may be a little hard to read

[
  {
    id: 2,
    first_name: "john",
    last_name: "john",
    malls: [
      {
        id: 1,
        name: "Ginger mall",
        slug: "Ginger-mall",
        pivot: {
          user_id: 2,
          mall_id: 1,
          id: 1
        },
        shop: [
          {
            id: 1,
            mall_id: 1,
            title: "Report 1"
          }
        ]
      }
    ]
  }
];

  

     

Upvotes: 0

Views: 325

Answers (2)

I'm wondering what your data field is?
You can compute a new array with duplicate id by computed key, for better performance.
You can refer to this example.

<template>
    <section class="second-section">
        <div class="row">
            <p>Numbers:</p>
            <li v-for="n in numbers" :key="n.id"> {{ n }}</li>
            <p>Even Numbers:</p>
            <li v-for="n in evenNumbers" :key="n.id">{{ n }}</li>
            <p>Odd Numbers:</p>
            <li v-for="n in oddNumbers" :key="n.id">{{ n }}</li>
        </div>
    </section>
</template>

<script>
export default {
    name: 'second-section',
    data () {
        return {
            numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        }
    },

    computed: {
        evenNumbers: function () {
            return this.numbers.filter(function (number) {
                return number % 2 === 0
            })
        },
        oddNumbers: function () {
            return this.numbers.filter(function (number) {
                return number % 2 === 1
            })
        }
    }
}
</script>

Upvotes: 0

gurumaxi
gurumaxi

Reputation: 486

You can use a method (source:https://stackoverflow.com/a/56757215/11484454) which removes all duplicate keys from your array (In this case, we assume entries with same ids are duplicates):

{
    methods: {
         filteredList(array) {
              return array.filter((v,i,a) => a.findIndex(t => (t.id === v.id)) === i)
         }
    }
 }

Then use it in your html template:

  <div class="detail-report-item" v-for="detail in filteredList(shop.shop)" :key="detail.id" :id="detail.id">

Upvotes: 1

Related Questions