javascript - Vue 计算方法 - 在数组中查找值不起作用

标签 javascript vue.js vuex

我有一个 Vue 页面来按类别显示食谱:

<template>
  <div class="recipes-page">
    <div class="recipes" v-for="r in categoryRecipes" :key="r.id">
      <span>{{ r.title }}</span>
    </div>
  </div>
</template>

<script>
export default {
  computed: {
    loadedRecipes() {
      return this.$store.getters.loadedRecipes;
    },
    loadedCategories() {
      return this.$store.getters['categories/loadedCategories'];
    },
    categoryRecipes() {
      let categorized = [];
      this.$store.getters['categories/loadedCategories'].forEach(cat => {
        this.$store.getters.loadedRecipes.forEach(recipe => {
          if (cat.id in Object.keys(recipe.categories)) { // doesnt work
            console.log("Recipe has the category with id: " + cat.id);
            categorized.push(recipe);
          }
        });
      });
      return categorized;
    }
  }
};
</script>

在数据结构中,我们有类别和配方:

类别:

[                                                                                                                                              
  {
    name: 'Juices',
    recipes: {
      '-L_Pg_BbwMYaGQjI2ejd': true
    },
    id: 'juices'
  },
  {
    name: 'Misc',
    recipes: {
      '-L_Pg_BbwMYaGQjI2ejd': true,
      '-L_PjcLaCvhZr9nb6wbh': true
    },
    id: 'misc'
  }
]

食谱:

[                                                                                                                                              
  {
    author: 'Ian K',
    categories: {
      juices: true,
      misc: true
    },
    citation: 'none',
    cookTime: 'n/a',
    created: '2019-03-08T00:27:09.774Z',
    description: 'How to make Orange Juice from frozen concentrate.',
    directions: 'Mix frozen orange juice and water in a pitcher.',
    featured: true,
    id: '-L_Pg_BbwMYaGQjI2ejd',
    prepTime: '1 min',
    starCount: 5,
    thumbnail: 'https://baconmockup.com/420/420',
    title: 'Orange Juice from Concentrate',
    totalTime: '1 min',
    updated: '2019-03-08T00:27:09.774Z',
    yield: '8 Cups'
  },

  ...
]

问题是 if 语句永远不会返回 true,即使 cat.id 确实存在于配方类别键中。有谁知道为什么检查键数组内容不起作用?

我还想知道像这样的链接迭代是否会对性能产生负面影响,以及是否有更好/更方便的方法来实现?

最佳答案

由于 Object.keys() 返回一个数组,您可能需要类似的东西

if (Object.keys(recipe.categories).includes(cat.id)) {

关于javascript - Vue 计算方法 - 在数组中查找值不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55129058/

相关文章:

javascript - 如何用Django REST Framework实现实时更新?

javascript - 如何在 Node.js 中设置和访问类属性?

vue.js - 访问 Vue3 全局组件

vue.js - 在 vue-cli 3 项目中使用带有 npm-link 的 vuex store 丢失 $store

javascript - 正确使用 D3 `data` 方法并传递函数和数据集

javascript - 如何检查浏览器对功能/事件的支持?

javascript - Webpack vue-loader 为单页 .vue 组件提供 "unexpected token {"

vue.js - 如何在v-for中获取键、值和索引

javascript - 何时再次通过 Vuex 从 API 获取数据以保持数据最新

typescript :引用 Vuex 商店模块为 VueJs 2.5 提供命名空间错误