0

This is the JSON object that I'm passing to the page, its called "orders"

[
 {
   orderID: '5f69df7fb852e822bc1524e8',
   customerName: 'John',
   productIDs: [
     '5f622bf4ee562b1d645ec09c',
     '5f639ce70facd65c5c8e135e',
     '5f69dddfd62fc74258103faa'
   ],
   productNames: [ 'product1', 'product2', 'product3' ],
   quantity: [ '1', '1', '1' ]
 }
] 

Example code:

{{#each orders}}
    <form action="/edit/{{._id}}" method="post">
        <label for="customerName">Customer's name</label>

        {{! This works fine }}
        <input type="text" value={{customerName}}>
        <hr>
        <p>Products:</p>
        {{#each productNames}}
            <label for="productNames">{{this}}</label>
            {{! Here I want the value of "quantity" which has the same index as the product name }}
            <input value="" type="number"> 
        {{/each}}
    </form>
{{/each}}

What I'm trying to achieve:

What im trying to achieve

When I use a nested #each, I get an error when trying to access the child array.

romellem
  • 5,792
  • 1
  • 32
  • 64
KF3
  • 47
  • 4
  • 1
    What does the Error say? – 76484 Sep 28 '20 at 14:19
  • i used the "each loop" to print out the products names, but in the same time i want to use a nested loop so that i can read the quantity object and display the quantity based on the index of the product name, every time i try to use the nested loop i just cant use "this" to red the quantity object so the page doesn't print anything – KF3 Sep 28 '20 at 15:43
  • I think a good starting point is to include the code you have tried so that others can identify the problem and help you solve it. – 76484 Sep 28 '20 at 16:21
  • will do it now. – KF3 Sep 28 '20 at 16:46
  • just updated the code – KF3 Sep 28 '20 at 16:57
  • 1
    You will need to use the lookup built-in helper. The documentation is here: https://handlebarsjs.com/guide/builtin-helpers.html#lookup. Additonally, a Stackoverflow answer (of mine) to a similar question can be found here: https://stackoverflow.com/a/54274111/3397771 – 76484 Sep 28 '20 at 19:06
  • Thank you so much <3 – KF3 Sep 28 '20 at 20:07

1 Answers1

0
  1. The #each helper exposes a variable @index within its context.
  2. The lookup helper allows for dynamic parameter resolution using Handlebars variables.
  3. The ../ prefix in a path allows your to change contexts up to a parent.

Combining these ideas together gives the following solution:

{{#each orders}}
    <form action="/edit/{{._id}}" method="post">
        <label for="customerName">Customer's name</label>
        <input type="text" value={{customerName}}>
        <hr>
        <p>Products:</p>
        {{#each productNames}}
            <label for="productNames">{{this}}</label>

            {{! Grab the corresponding parent `quantity` value using the current index }}
            <input value="{{lookup ../quantity @index}}" type="number">

        {{/each}}
    </form>
{{/each}}
romellem
  • 5,792
  • 1
  • 32
  • 64