user1897933
user1897933

Reputation: 13

how to get the json key value pair in specific format

i have json array like below:

var region= [{"af":"Africa"},{"as":"Asia"},{"au":"Australia"}]

I am using some framework in that i got value of above array as:

{for r in regions}
     <option value="${r}" >${r}</option>
{/for}

i tried javascript but didn't succeded. I want the output in above format

plz help me out this.

Upvotes: 0

Views: 569

Answers (1)

zerkms
zerkms

Reputation: 254944

var region= [{"af":"Africa"},{"as":"Asia"},{"au":"Australia"}],
    len = region.length,
    i, key;

for (i = 0; i < len; ++i) {
    key = Object.keys(region[i])[0];
    console.log(key, region[i][key]);
}​

Object.keys in this code returns an array of all keys of the object. And as long as you have 1 and only 1 key per object - you just retrieve the first using [0]

http://jsfiddle.net/zerkms/hYFHy/

Upvotes: 1

Related Questions