2

我的 JSON看起来像这样:

{
  "features": [
    {
      "id": "belly",
      "scenarios": [
        {
          "id": "belly;a-few-cukes",
          "tags": [
            {
              "name": "@tag1"
            }
          ],
          "steps": [
            {
              "name": "I have 42 cukes in my belly"
            },
            {
              "name": "I wait 1 hour"
            },
            {
              "name": "my belly should growls"
            }
          ]
        },
        {
          "id": "belly;a-few-cukes-with-new-test",
          "tags": [
            {
              "name": "@tag2"
            }
          ],
          "steps": [
            {
              "name": "I have 42 cukes in my belly"
            },
            {
              "name": "I wait 1 hour"
            },
            {
              "name": "my belly should growl"
            }
          ]
        }
      ]
    },
    {
      "id": "newbelly",
      "scenarios": [
        {
          "id": "newbelly;a-few-cukes-with-new-feature",
          "tags": [
            {
              "name": "@tag1"
            }
          ],
          "steps": [
            {
              "name": "I have 42 cukes in my belly"
            },
            {
              "name": "I wait 1 hour"
            },
            {
              "name": "my belly should growls"
            }
          ]
        }
      ]
    }
  ]
}

我想检索所有唯一的标签名称:即@tag1、@tag2。如果您注意到,@tag1 会重复两次。

我的模板

{{#getTags features}}
    {{#scenarios}}
        {{#tags}}
            <p>{{name}}</p>
        {{/tags}}
    {{/scenarios}}
{{/getTags}}

到目前为止我创建的自定义助手:

Handlebars.registerHelper('getTags', function(context, block) {
    var ret = "";

    for (var i = 0; i < context.length; i++) {
        ret += block.fn(context[i]);
    };

    return ret;
});

上面的自定义助手返回所有标签,但我想要唯一的。

4

1 回答 1

1

这些方面的东西可能会起作用:

Handlebars.registerHelper('getTags', function(context, block) {
var ret = "";
var got = [];

function contains(obj, a) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
return false;
}

for (var i = 0; i < context.length; i++) {
    if (!this.contains(context[i],got)) {
        got.addObject(context[i]);
        ret += block.fn(context[i]);
    }
}

return ret;
});

用于测试的代码,所有的javascript:

var ret = "";
var got = [];
var data = ["tag1", "tag1", "tag2", "tag3"]

function contains(obj, a) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
return false;
}

for (var i = 0; i < data.length; i++) {
    if (!contains(data[i],got)) {
        got.push(data[i]);
        ret += data[i];
        }
}

console.log( ret);
于 2015-03-24T13:36:54.530 回答