是否有一种内置方法来循环对象的属性

Is there a built-in way to loop through the properties of an object?

本文关键字:方法 循环 对象 属性 内置 一种 是否      更新时间:2023-09-26
是否有一种胡

须/车把循环对象属性的方式?

所以用

var o = {
  bob : 'For sure',
  roger: 'Unknown',
  donkey: 'What an ass'
}

然后我可以在模板引擎中做一些等效的事情吗

for(var prop in o)
{
    // with say, prop a variable in the template and value the property value
}

内置支持,自车把 1.0rc1 起

对此功能的支持已添加到 Handlebars.js,因此不再需要外部助手。

如何使用它

对于数组:

{{#each myArray}}
    Index: {{@index}} Value = {{this}}
{{/each}}

对于对象:

{{#each myObject}}
    Key: {{@key}} Value = {{this}}
{{/each}}

请注意,将仅枚举通过hasOwnProperty测试的属性。

实际上很容易

实现为帮助程序:

Handlebars.registerHelper('eachProperty', function(context, options) {
    var ret = "";
    for(var prop in context)
    {
        ret = ret + options.fn({property:prop,value:context[prop]});
    }
    return ret;
});

然后像这样使用它:

{{#eachProperty object}}
    {{property}}: {{value}}<br/>
{{/eachProperty }}

编辑:Handlebars现在有一种内置的方式来实现这一目标;请参阅上面的所选答案。使用普通小胡子时,以下内容仍然适用。

胡子可以迭代数组中的项目。所以我建议创建一个单独的数据对象,格式为Mustache可以使用:

var o = {
  bob : 'For sure',
  roger: 'Unknown',
  donkey: 'What an ass'
},
mustacheFormattedData = { 'people' : [] };
for (var prop in o){
  if (o.hasOwnProperty(prop)){
    mustacheFormattedData['people'].push({
      'key' : prop,
      'value' : o[prop]
     });
  }
}

现在,您的胡须模板将是这样的:

{{#people}}
  {{key}} : {{value}}
{{/people}}

在此处查看"非空列表"部分:https://github.com/janl/mustache.js

这是@Ben的答案更新为与Ember一起使用...注意 您必须使用 Ember.get,因为上下文是作为字符串传入的。

Ember.Handlebars.registerHelper('eachProperty', function(context, options) {
  var ret = "";
  var newContext = Ember.get(this, context);
  for(var prop in newContext)
  {
    if (newContext.hasOwnProperty(prop)) {
      ret = ret + options.fn({property:prop,value:newContext[prop]});
    }
  }
  return ret;
});

模板:

{{#eachProperty object}}
  {{key}}: {{value}}<br/>
{{/eachProperty }}

@Amit的答案很好,因为它可以在胡须和车把中工作。

就仅车把解决方案而言,我已经看到了一些,我喜欢 https://gist.github.com/1371586 最好的each_with_key块助手。

  • 它允许您迭代对象文本,而无需先重新构建它们,并且
  • 它使您可以控制所谓的关键变量。 对于许多其他解决方案,您必须小心使用名为 'key''property' 等的对象键。

感谢 Ben 的解决方案,我的用例是按顺序仅显示特定字段

带对象

法典:

    handlebars.registerHelper('eachToDisplayProperty', function(context, toDisplays, options) {
    var ret = "";
    var toDisplayKeyList = toDisplays.split(",");
    for(var i = 0; i < toDisplayKeyList.length; i++) {
        toDisplayKey = toDisplayKeyList[i];
        if(context[toDisplayKey]) {
            ret = ret + options.fn({
                property : toDisplayKey,
                value : context[toDisplayKey]
            });
        }
    }
    return ret;
});

源对象:

   { locationDesc:"abc", name:"ghi", description:"def", four:"you wont see this"}

模板:

{{#eachToDisplayProperty this "locationDesc,description,name"}}
    <div>
        {{property}} --- {{value}}
    </div>
    {{/eachToDisplayProperty}}

输出:

locationDesc --- abc
description --- def
name --- ghi

这是 mustacheJS 的一个帮助函数,无需预先格式化数据,而是在渲染期间获取数据。

var data = {
    valueFromMap: function() {
        return function(text, render) {
            // "this" will be an object with map key property
            // text will be color that we have between the mustache-tags
            // in the template
            // render is the function that mustache gives us
            // still need to loop since we have no idea what the key is
            // but there will only be one
            for ( var key in this) {
                if (this.hasOwnProperty(key)) {
                    return render(this[key][text]);
                }
            }
        };
    },
    list: {
        blueHorse: {
            color: 'blue'
        },
        redHorse: {
            color: 'red'
        }
    }
};

模板:

{{#list}}
    {{#.}}<span>color: {{#valueFromMap}}color{{/valueFromMap}}</span> <br/>{{/.}}
{{/list}}

输出:

color: blue
color: red

(顺序可能是随机的 - 这是一张地图(如果您知道所需的地图元素,这可能很有用。只要注意虚假的价值观。

我使用的是旧版本的车把1.0.beta.6,我认为在 1.1 - 1.3 期间的某个地方添加了此功能,因此更新到 1.3.0 解决了这个问题,这是用法:

用法:

{{#each object}}
  Key {{@key}} : Value {{this}}
{{/people}}