Feb 28, 2013

JSON array of objects

It can be a situation where you got a array of data that should be sent in the JSON format to server via ajax, then you can do the following

<script type="text/javascript" >
groups = ['A', 'B', 'C'];
users  = ['user1', 'user2', 'user3'];

//required format is  [{"group_name" : "A", "leader" : "user1"}, {"group_name" : "B", "leader" : "user2"}, {"group_name" : "C", "leader" : "user3"}]

group_leaders = new Array();

len = groups.length;

for(var i = 0; i < len; i++ ){
    group_leaders.push({"group_name" : groups[i], "leader" : users[i]});
}

alert(JSON.stringify(group_leaders));
</script>

Here you can test here http://jsfiddle.net/sailesh/6wXdY/

No comments:

Post a Comment

Want to tell something about this post. Please feel free to write...