Saswat
Saswat

Reputation: 12856

Creating a jQuery array based on key of json array

I have a json array thats being sent up by ajax response.

The json array is in the following manner

[{"id":"11105","name":"Gummy Drop (iPhone, Free, ROW except CN, 72.3MB, w"},{"id":"11107","name":"Gummy Drop (iPad, Free, ROW except CN, 72.3MB, w\/ "},{"id":"4274","name":"Z-Redirect Non-Targeted Traffic Dragon City Mobile"},{"id":"6484","name":"Z-Redirect Non-Targeted Traffic Dragon City Mobile"}]

Now, sometimes, the key can be id and name, sometimes it can be roll and address

So it's not always predictable or some.

I need to get the key form this JSON array/object and build some thing like this

var aColumns = [{ sTitle: "id"}, { sTitle: "name" }];

Someone suggested me a piece of code, which is as follows:

$.post("ajax.php",{'version':v,'category':ctg,'country':cnt,'func':'show_datatable'},
                        function(data)
                        {
                            /*var aColumns = [{ sTitle: "Week"}, { sTitle: "Winkelformule" }];*/
                            for(var i = 0; i < data.length; i++) 
                            {
                                keycolumns = Object.keys(data[i]); 
                                for(j = 0; j < keycolumns.length; j++)
                                {
                                    alert(keycolumns[j]);
                                    if($.inArray(keycolumns[j],aColumns.sTitle)<=0)
                                    {
                                        aColumns.push({sTitle: keycolumns[j]}) //Checks if 
                                    }                                     
                                }
                            }
                       },'json');

It seems his idea is right, but something is fishy in these lines:

if($.inArray(keycolumns[j],aColumns.sTitle)<=0)
    {
        aColumns.push({sTitle: keycolumns[j]}) //Checks if 
    }

Upvotes: 0

Views: 77

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77522

var aColumns = [];

data.forEach(function (el) {    
    Object.keys(el).forEach(function (key) {
        if (!~aColumns.indexOf(key)) {
            aColumns.push(key);
        }
    })
})

aColumns = aColumns.map(function (key) {
    return {sTitle: key};
});

console.log(aColumns);

Demo: http://jsfiddle.net/e50rwfbr/

-- this line is not correct

if($.inArray(keycolumns[j], aColumns.sTitle)<=0)

you need check in aColumns not keycolumns.. like this

var aColumns = [], i, j;

for(i = 0; i < data.length; i++) {
    keycolumns = Object.keys(data[i]);

    for (j = 0; j < keycolumns.length; j++) {
        if (!aColumns.length || !aColumns.filter(function(el) { return el.sTitle == keycolumns[j]; }).length) {
            aColumns.push({sTitle: keycolumns[j]});
        }                                
    }
}

DEMO: http://jsfiddle.net/e50rwfbr/2/

Upvotes: 1

Related Questions