简体   繁体   English

使用一个对象值作为键来访问把手中的其他对象值

[英]Use one object value as a key to access other object value in Handlebars

I have 2 different objects: 我有2个不同的对象:

1) In global.json 1)在global.json中

var objA = {
    "menu": {
        "icon": [
            {
                "network": "mail",
            },
            {
                "network": "facebook",
            },
            {
                "network": "twitter",
            },
            {
                "network": "googleplus",
            }
        ]
    }
}

2) In index.json 2)在index.json中

var objB = {
    "facebook": {
        "data": "Facebook Data",
    },
    "twitter": {
        "data": "Twitter Data",
    },
    "mail": {
        "data": "Mail Data",
    },
    "googleplus": {
        "data": "GooglePlus Data",
    }
}

Now I want to access the second object value by using first object value as a key in .hbs file, just like we do in javascript. 现在,我想通过将第一个对象值用作.hbs文件中的键来访问第二个对象值,就像在javascript中一样。

Like for example: If I want to access twitter data, I will use the following code in javascript to access that. 例如:如果我想访问Twitter数据,我将使用javascript中的以下代码来访问它。

for(var i=0; i<objA["menu"]["icon"].length; i++){
    console.log(objB[objA["menu"]["icon"][i]["network"]]["data"]);
}

I am running a each loop in a .hbs file: 我正在.hbs文件中运行每个循环:

{{#each global.objA.menu.icon}}
    <li>{{data}}</li>
{{/each}}

Here I want to show each social data based on the network . 在这里,我想显示基于网络的每个社交数据

I have zero knowledge about handlebars, but assuming it is at least a javascript, 我对车把的知识为零,但假设它至少是JavaScript,

data = objA.menu.icon.map(e=>objB[e.network])

should fulfill your last object desire. 应该满足您的最后一个对象欲望。

 var objA = { "menu": { "icon": [ { "network": "mail", }, { "network": "facebook", }, { "network": "twitter", }, { "network": "googleplus", } ] } }; var objB = { "facebook": { "data": "Facebook Data", }, "twitter": { "data": "Twitter Data", }, "mail": { "data": "Mail Data", }, "googleplus": { "data": "GooglePlus Data", } }; data = objA.menu.icon.map(e=>objB[e.network]) console.log(data); 

You can accomplish this using a combination of the lookup and with built-in helpers. 您可以使用组合完成这个查找使用内置的助手。 lookup acts as a way to use variable keys and with sets a context to allow you to access each network object's properties. lookup是使用变量键的一种方式,并with设置上下文来允许您访问每个网络对象的属性。

{{#each global.objA.menu.icon}}
  {{#with (lookup @root/global/objB this.network)}}
    {{data}}
  {{/with}}
{{/each}}
// outputs (no formatting)
// 'Mail DataFacebook DataTwitter DataGooglePlus Data'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM