jQuery .getJSON return into array variable & json array manipulation

ZolaKt picture ZolaKt · Mar 11, 2011 · Viewed 13.9k times · Source


is there any way I can get the return of $.getJSON into a variable array?
I know its async and out of scope, but I will use it inside ajax callback, I just need to get all the values first and check them against another array.

Something like:

$.getJSON('itemManager.php?a=getItems', function(data){
    // itemArray = new Array(data);
    // idsArray = new Array(data.id);
    for (var i in someOtherArray){
        if($.inArray(i, idsArray) == -1){
            // do something...
            // get jason variable by id?
            // itemArray[i].someVariable
        }
    }
}

EDIT: JSON structure

[{"id":"786","user_id":"1","seller_id":"2","address_id":"1","time":1299852115,"publicComment":null,"personalComment":null},
{"id":"787","user_id":"1","seller_id":"2","address_id":"1","time":1299852115,"publicComment":null,"personalComment":null},
{"id":"785","user_id":"1","seller_id":"2","address_id":"1","time":1299852114,"publicComment":null,"personalComment":null},
{"id":"784","user_id":"1","seller_id":"2","address_id":"1","time":1299852113,"publicComment":null,"personalComment":null},
{"id":"783","user_id":"1","seller_id":"2","address_id":"1","time":1299852111,"publicComment":null,"personalComment":null}]

This is basically the idea.

  • Get all the values
  • Isolate the id values of JSON objects
  • Loop another array
  • Check if json id is inside the other array
  • Access other json variables by id value

There are various solutions here I guess, but I'm looking for something with minimal code.

Answer

Felix Kling picture Felix Kling · Mar 11, 2011

With the given information, there is not shortcut to test the existence of IDs. You really have to loop over everything. However you can improve a bit by creating an id => object mapping:

$.getJSON('itemManager.php?a=getItems', function(data){
    var items = {};
    for(var i = data.length; i--; ) {
        items[data[i].id] = data[i];
    }
    for (var j = someOtherArray.length; j--; ){
        var item = items[someOtherArray[j]];
        if(item){
            // do something with `item`
        }
    }
}

It woud be even better if you create this structure on the server already, then it would be:

$.getJSON('itemManager.php?a=getItems', function(data){
    for (var j = someOtherArray.length; j--; ){
        var item = data[someOtherArray[j]];
        if(item){
            // do something with `item`
        }
    }
}

You should also consider which arrays will contain more elements, data or someOtherArray and adjust your data structures such that you loop over the smaller array only.

Update:

To create the appropriate structure on the server with PHP, you have to create an associate array.

So at the point where you add an object to the array, you should not do

$items[] = $obj;

but

$items[$obj->id] = $obj; // or $obj['id'] if you have an array