【问题标题】:How to filter an array by another array in vue如何在vue中通过另一个数组过滤数组
【发布时间】:2021-04-04 04:17:42
【问题描述】:

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

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>

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

【问题讨论】:

    标签: javascript vue.js filter


    【解决方案1】:

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

    computed properties in vue js

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

    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;
          }, []);
        },
      },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 2020-01-27
      • 2021-12-22
      • 2017-02-24
      • 2020-11-25
      相关资源
      最近更新 更多