我有一个 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/