Pit Digger
Pit Digger

Reputation: 9780

Extract data to array from ajax call

I have following response reurned from an AJAX call to success function

{"0":"A",
"1":"B",
"2":"C",
"saved_as":["M","K","L"]}

Is there any way to have it in an array like following

dataObj[0]="A";
dataObj[1]="B";
dataObj[2]="C";

On a side not returned data can have more that first three elements . Last element will always be saved_as

Thanks.

Upvotes: 0

Views: 310

Answers (1)

user113716
user113716

Reputation: 322452

If you just want the numeric properties (which would make sense), you could do this:

var array = [];

for( var name in dataObj ) {
    if( !isNaN( +name ) ) {
        array[ name ] = dataObj[ name ];
    }
}

DEMO: http://jsfiddle.net/hW8Jm/

(I assume the JSON data has already been parsed.)

This enumerates the properties of dataObj, attempts a toNumber conversion using the unary + operator, and then checks to see if the result is NaN (Not a Number).

If it's not NaN (it is a Number), then the value of that property is added to the array using the property as the index of the array.

Upvotes: 3

Related Questions