javascriptnode.jshandlebars.jsexpress-handlebarshandlebarshelper

Show different JSON objects inside loop of other object in Handlebars for a condtition


I am rendering two different objects from JS file to HBS file. Let these objects be Obj1 and Obj2. On the HBS file, I am looping Obj1 in a table. But at some row of the table, I want to access Obj2. I am not able to access that.

home.hbs

<tbody>
    {{#Obj1}}
    <tr>
        <td>{{Name}}</td>            //From Obj1 (Working Fine)
        <td>{{Place}}</td>          //From Obj1  (Working Fine)
        <td>{{Obj2.Country}}</td>  //Here I want to access value from Obj2 if Obj1.Name==Obj2.Name
    </tr>
    {{/Obj1}}
</tbody>

JS

res.render('home',{
   Obj1: personData;
   Obj2: countryData;
})

Objects

Obj1=[{Name: John, Place: New York},{Name: Raman, Place: New Delhi}]

Obj2=[{Name: John, Country: USA},{Name: Raman, Country: India}]


Solution

  • First, if it is at all possible, I would advise you to alter your data structure. Since it is clear from the sample arrays you provided, the data in each array (Obj1 and Obj2) are strongly related. It makes much more sense to have a single array with objects like:

    {
      "Name": "John",
      "Place": "New York",
      "Country": "USA"
    }
    

    than it does to split the Place and Country across objects in separate arrays, linked by the array index.

    Aside: I would also recommend renaming these variables - "Obj1" and "Obj2" - because they are arrays, which is more specific than object.

    However, if you absolutely must use the two arrays, it is possible to get a property from one array while iterating through the other with the use of a context path, the lookup helper, and the @index data-variable.

    What we want to do is: inside our loop of the array Ojb1, get object from the array Obj2 at the corresponding iteration index and get its Country property.

    Handlebars provides a convenience data variable, @index, which can be used within a loop to get the current iteration index. We can use this to lookup the object in Obj2 at the same index: lookup ../Obj2 @index. Note that we must prefix Obj2 with ../ which tells Handlebars that we must step up a single context level to where Obj1 and Obj2 live. Once we have that object, we can use a second lookup to get its Country property.

    The full code becomes:

    {{lookup (lookup ../Obj2 @index) 'Country'}}
    

    The parentheses are necessary because the nested lookup is a subexpression.

    I have created a fiddle for your reference.