0

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@Sonesh Dabhi: If you're using jQuery's AJAX methods, then if you simply give it a json dataType, jQuery will make sure it gets parsed. Otherwise you use var parsedObj = JSON.parse(dataObj) to parse it. To support older browsers, you can include the JSON2 library.
var dataObj = eval('('+data+')'); I am not sure whats difference between the two but this worked.
@Sonesh Dabhi: If you're receiving JSON data, then parse it as JSON. It is a secure way to receive and parse data since JSON will not allow executable code to be parsed and evaluated. If you use .eval(), any malicious code that may find its way in will be executed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.