silvesterprabu
silvesterprabu

Reputation: 1457

how to show json object key and value using handlebar template?

I have started to learn handlebar.js . I am struggling to display json data .

My json look like this:

 var data={
          "record1":
          [
             {
               "first":
                      [
                       {
                         "name":"john",
                         "city":"newyork"  
                       },
                       {
                         "name":"britto",
                         "city":"bangalore"  
                       }
                      ]
             },
            {"second":
                 [
                  {
                    "name":"franklin",
                    "city":"newyork"  
                  },
                  {
                    "name":"leo",
                    "city":"bangalore"  
                  }
                ]
            }
        ]
    };

here this json is coming from server response so I don't know any key and value. I have to show key and value dynamically by using handlebar ...I have tried with eachKey but I have not got solution for that . Can anyone help me?

Upvotes: 18

Views: 22492

Answers (3)

RegarBoy
RegarBoy

Reputation: 3521

For objects:

{{#each myObject}}
    Key: {{@key}} Value = {{this}} //renders object like {key: value}
{{/each}}

Note that only properties passing the hasOwnProperty test will be enumerated.


For arrays:

{{#each myArray}}
    Index: {{@index}} Value = {{this}}
{{/each}}

Upvotes: 2

nerdlyist
nerdlyist

Reputation: 2857

First thank you tobi this did lead to what I needed getting the key.

In case it was not clear for the OP "this" is referring to the current object of that iteration.

So in your case data the object has the array record1 with 2 objects that are arrays of objects: first and second.

Using each:

{{#each record1}}
    {{@key}}: {{this}}
{{/each}}

would give you: first: (object, array) second: (object, array)

You will be looping over the object (data). In this if you wanted to dig down you would need a counter to get anywhere further. I would recommend using a handlebars block helper to get there.

Here is the documentation: http://handlebarsjs.com/block_helpers.html

Upvotes: 3

tobi
tobi

Reputation: 789

You can render the keys/values of a list in a Handlebars template like this:

{{#each object}}
  {{@key}}: {{this}}
{{/each}}

Upvotes: 34

Related Questions