sort #each loop



  • I have this json data:
    {
    "year": 1986,
    "data" : {
    "3": {"Name": "Charlie"},
    "1": {"Name": "Alice"},
    "2": {"Name": "Bob"}
    }
    }

    and I am trying create a pdf report with 3 pages. if I use this
    {{#each data}}
    <h1>Title: {{@key}}</h1>
    {{/each}}

    O obtain 1, 2, 3. I need the original order 3 1 2
    Is it possible to maintain the order?


  • administrators

    hi @giova86

    object keys order are not guaranteed, this is behaviour is part of js language, if you need a very specific order, use an array, if you don't want to change the data input then you can convert the object to array at runtime with a helper

    function toSortedArrayByKey(data) {
      const arr = []
    
      const sortedKeys = Object.keys(data).map((key) => (
        parseInt(key, 10)).sort((a, b) => a - b)
      )
    
      return sortedKeys.map((key) => data[key])
    }
    

    and use it like this:

    {{#each (toSortedArrayByKey data)}}
    

Log in to reply
 

Looks like your connection to jsreport forum was lost, please wait while we try to reconnect.