views:

46

answers:

6

Consider a string which is

{"Table" : [{"Bird" : "Peacock"},
{"Bird" : "Crow"}]}

to this ["Peacock", "Crow"] in jquery... Is this possible?

EDIT: I am doing this but didnt work...

$(document).ready(function() {
                var obj = JSON.parse('{"Table" : [{"Bird" : "Peacock"},{"Bird" : "Crow"}]}');
                myarray = [];

                $.each(obj.table, function(i, v) {
                    myarray.push(v.Bird);
                });
                $("#tags").autocomplete(myarray, {
                    width: 138,
                    max: 4,
                    highlight: false,
                    multiple: true,
                    multipleSeparator: " ",
                    scroll: true,
                    scrollHeight: 300
                });
            });
+1  A: 

You can do it in simple javascript:

var obj={"Table" : [{"Bird" : "Peacock"},{"Bird" : "Crow"}]};
var tables=obj.Table,i,ret=[];
for(i=0;i<tables.length;i++)
    ret.push(tables[i].Bird);

Then in the variable ret you'll have the result array

mck89
+1  A: 

If it's a string, you can use parseJSON to turn it into an object (for jQuery 1.4+). Otherwise, skip the first line:

var s = '{"Table" : [{"Bird" : "Peacock"},{"Bird" : "Crow"}]}';

var data = $.parseJSON(s);
var table = data.Table;
var birds = [];
for(var i = 0; i< table.length;i++){
    birds.push(table[i].Bird);
}

alert(birds); //Peacock,Crow
Kobi
+1  A: 
var list = {"Table" : [{"Bird" : "Peacock"},{"Bird" : "Crow"}]};
var newList = $.map(list.Table, function(item) {
    return item.Bird
});
PetersenDidIt
+1  A: 
var obj = JSON.parse('{"Table" : [{"Bird" : "Peacock"},
          {"Bird" : "Crow"}]}'),
    myarray = [];

 $.each(obj.table, function(i,v){
    myarray.push(v.Bird);
 });
jAndy
+1  A: 
var s = '{"Table" : [{"Bird" : "Peacock"},{"Bird" : "Crow"}]}'

var result = '[' + $.map($.parseJSON(s).Table, function(el) {
    return '"' + el.Bird + '"';
}).join(', ') + ']';

Functional style rules. Although, I'm not sure you really want string as output. If not:

var result = $.map($.parseJSON(s).Table, function(el) {
    return el.Bird;
});
vava
+1  A: 

You can use the parseJSON method (requires jQuery 1.4.1 or later) to parse the string, then the map method to get the Bird property from each item:

var str = '{"Table" : [{"Bird" : "Peacock"},{"Bird" : "Crow"}]}';
var arr = $.map($.parseJSON(str).Table, function(e){ return e.Bird; });

If it's not a string but an object, you just need the map method:

var obj = {"Table" : [{"Bird" : "Peacock"},{"Bird" : "Crow"}]};
var arr = $.map(obj.Table, function(e){ return e.Bird; });
Guffa