首页 > 解决方案 > 如何在vue中通过另一个数组过滤数组

问题描述

我有两个对象数组,其中一个称为子模块,其中有一个子数组,我需要通过访问的对象数组过滤这些子数组

new Vue({
  data: {
    submodules: [
      {
          type: "something1",
          children: [
              {
                  name: "new_sth1",
                  value: "new_sth1"
              },
              {
                  name: "new_sth2",
                  value: "new_sth2"
              }
          ]
      },
      {
          type: "something2",
          children: [
              {
                  name: "new_sth3",
                  value: "new_sth3"
              },
          ]
      },
      {
          type: "something3",
          children: [
              {
                  name: "new_sth4",
                  value: "new_sth4"
              },
              {
                  name: "new_sth5",
                  value: "new_sth5"
              },
              {
                  name: "new_sth6",
                  value: "new_sth6"
              },
          ]
      },
    ],
    accessed: [
      {value: 'new_sth1'},
      {value: 'new_sth2'},
      {value: 'new_sth3'},
      {value: 'new_sth4'},
    ]
  }
})
<div class="row">
    <div class="col-6 mt-3" v-for="item in submodules">
        <div class="card" style="min-height: 260px">
            <div class="card-header" style="background: #757575;color: white">
                {{item.type}}
            </div>
            <div class="card-body">
                <ul class="nav nav-pills nav-stacked mb-0 pb-0">
                    <li style="width: 100%;cursor: pointer" class="navbar my-0 py-0" v-for="child in                                              item.children">
                        <a style="color: black" :href="'/'+child.value">
                            <span class="text-right navbar-text">{{child.name}}</span>
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</div>

我需要通过访问的数组值过滤子模块数组。我尝试了很多方法,但我无法解决问题。如果有人有任何想法,请与我分享。

标签: javascriptvue.jsfilter

解决方案


您可以使用computed属性来根据 过滤submodules数组accessed

vue js中的计算属性

codeandbox:代码没有样式,因为我没有安装引导程序。

computed: {
    getFilteredResult() {
      return this.submodules.reduce((acc, curr) => {
        const children = curr.children.filter(({ value }) => {
          return this.accessed.find((x) => x.value === value);
        });
        acc.push({ ...curr, children });
        return acc;
      }, []);
    },
  },

推荐阅读