Search code examples
javascriptnode.jshandlebars.js

Looping Objects of Object with handlebars.js


I have a simple node.js app that returns the following json.

{
  computers: {
   john: {
     cpu: "intel",
     ram: "8MB",
     hd: "1TB"
   },
   jane: {
     cpu: "intel",
     ram: "12MB",
     hd: "500GB"
   },
   mary: {
     cpu: "intel",
     ram: "8MB",
     hd: "500GB"
   }
  }
}

in my index.hbs file I have the following.

{{#each computers}}
   {{#each this}}
      {{cpu}} {{ram}} {{hd}}
   {{/each}}
{{/each}}

I would like the get the following result.

John: intel, 8MB, 1TB jane: intel, 12MB, 500GB etc..

Any suggestion is greatly appreciated!


Solution

  • You don't have to create nested each. Simply using paths combined with @key to get current key of iterating object will do.

    {{#each computers}}
      {{@key}}: {{./cpu}}, {{./ram}}, {{./hd}}
    {{/each}}