1

I am using handlebars.js to iterate over categories, and then use the current array index to access an element in the series array. I am able to do so using the below helper.

var json={
    "categories": [{
            "id": 3,
            "name": "category 0"
        }, {
            "id": 6,
            "name": "category 1"
        }
    ],
    "series": [{
            "id": 1,
            "name": "DUMMY",
            "data": [{
                    "id": 5,
                    "name": "series 0 data 0"
                }, {
                    "id": 10,
                    "name": "series 0 data 1"
                }
            ]
        }
    ]
}

Handlebars.registerHelper('getArrayValues', function(ar, index, prop) {
    return ar[0].data[index][prop];
});

var template = Handlebars.compile(json);

{{#each categories}}
<p>id: {{this.id}}</p>
<p>name: {{this.name}}</p>
<p>series id with helper: {{getArrayValues ../series @index 'id' }}</p>
<p>series name with helper: {{getArrayValues ../series @index 'name' }}</p>
{{/each}}

Am I able to do so without a helper? Below is my attempt. I've also tried using lookup, but can seem to be able to access the properties that lookup returns.

{{#each categories}}
<p>id: {{this.id}}</p>
<p>name: {{this.name}}</p>
<p>series id: {{../series.[0].data.[@index].id}}</p>
<p>series name: {{../series.[0].data.[@index].name}}</p>
{{/each}}

1 Answer 1

1

One solution I founded for this, I do not know how much good it is but It is working perfectly

Try this :)

{{#each categories}}
  <p>id: {{this.id}}</p>
  <p>name: {{this.name}}</p>
  <p>series id with helper:{{#with (lookup  ../series.[0].data 
  @index) }}{{this.id}}{{/with}}</p>
  <p>series name with helper: {{#with (lookup  ../series.[0].data 
  @index) }}{{this.name}}{{/with}}</p>
{{/each}}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Nishant, While I am sure your answer is accurate (however, haven't tested), maybe I will stick with my silly helper function as it makes sense to me. Edit. Probably will change to yours.
Tested, and works perfect. I found #with documentation at handlebarsjs.com/builtin_helpers.html. Thanks
Can you please suggest what to do when series can also be an array of object. I tried this {{#with (lookup ../series.[@index].data @index) }}{{this.id}}{{/with}} but it doesn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.