简体   繁体   English

如何在Vuejs中隐藏内部数组中的重复项

[英]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我正在尝试从vuejs的嵌套数组中删除重复的键,并将它们从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.我的数据是通过 axios 从 Laravel api 获取的。 PS this may be a little hard to read PS 这可能有点难读

[
  {
    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"
          }
        ]
      }
    ]
  }
];

  

     

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):您可以使用一种方法(来源: https : //stackoverflow.com/a/56757215/11484454 )从数组中删除所有重复键(在这种情况下,我们假设具有相同 ID 的条目是重复的):

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

Then use it in your html template:然后在您的 html 模板中使用它:

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

I'm wondering what your data field is?我想知道你的数据字段是什么?
You can compute a new array with duplicate id by computed key, for better performance.您可以通过计算键计算具有重复 id 的新数组,以获得更好的性能。
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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM