javascript - 使用变量作为名称来访问另一个数组的嵌套元素

标签 javascript meteor spacebars

我为我在助手中构建的数组执行每个循环:

Template.article.helpers({
    section: function() {
        return [
            {type: 'cars', sectionTitle: 'Cars'}, 
            {type: 'vegetables', sectionTitle: 'Vegetables'}
        ];
    },
});

文章的数据来自路由器:

Router.route('/article/:_id', {
    name: 'article',
    data: function() {
        return {
            article: Articles.findOne({ _id: this.params._id })
        }
    }   
});

但现在我想使用助手的 type 访问 article 的子元素。所以在这个例子中,每个循环将执行两次:我首先要使用 ../article.cars,然后是 ../article.vegetable。我希望你能理解我的问题。我想通过助手类型获取子元素的名称:

<template name="article">
    {{#each section}}
        <h1>{{this.sectionTitle}}</h1>

        <ul>
        {{#each ../article.type}} <!-- should get '../article.cars' and '../article.vegetable' -->
            <li>{{this.title}}</li>
        {{/each}}
        </ul>
    {{/each}}
</template>

我想用type的内容作为变量名。如果类型是“汽车”,那么我想使用 ../articles.cars'。这将是类似于articles['cars']的结果articles[type]。但在 meteor 中,这种写法是不可能的。而articles.type` 则有所不同。

最佳答案

只需使用另一个助手:

s: function(article) {
    return article[this.type];
}

然后用你的空格键发送一个参数:

{{#each s ../article}}

关于javascript - 使用变量作为名称来访问另一个数组的嵌套元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32919817/

相关文章:

javascript - 在位置 X 插入值

Meteor Up Docker 和 Graphicsmagick

javascript - meteor 全局化: deployment to different languages

meteor - 如何从Meteor模板将多个参数传递给Spacebars helper?

javascript - 为什么 'mouseenter' 事件只适用于空格键的第一个元素 #each 迭代?

javascript - 具有相同定义的 Material ui多个类名

javascript - attachEvent 或 addEventListener - 存储在哪里?

mongodb - 在 Meteor 中使用带有参数的#each

Javascript:添加除数组中的元素之外的所有元素

javascript - 如何删除 ReactMeteorData 中的警告消息?