Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Actually I have an json object like this coming as an server response

{"0":"1","1":"2","2":"3","3":"4"}

SO I want to convert it into javascript array like

["1","2","3","4"]

Is there any good way to do this where ever I am reading people are using complex logic using loops. So Is there any other way to do this?

share|improve this question
 
duplicate : stackoverflow.com/questions/6857468/… –  Jahnux73 Jan 2 at 10:55
add comment

7 Answers

var json = '{"0":"1","1":"2","2":"3","3":"4"}';

var parsed = JSON.parse(json);

var arr = [];

for(var x in parsed){
  arr.push(parsed[x]);
}

Hope this is what you're after!

share|improve this answer
add comment

There is nothing like a "JSON object" - JSON is a serialization notation.

If you want to transform your javascript object to a javascript array, either you write your own loop [which would not be that complex!], or you rely on underscore.js _.toArray() method:

var obj = {"0":"1","1":"2","2":"3","3":"4"};
var yourArray = _(obj).toArray();
share|improve this answer
add comment

Nothing hard here. Loop over your object elements and assign them to the array

var obj = {"0":"1","1":"2","2":"3","3":"4"};
var arr = [];
for (elem in obj) {
   arr.push(obj[elem]);
}

http://jsfiddle.net/Qq2aM/

share|improve this answer
add comment

You simply do it like

var data = {
    "0": "1",
    "1": "2",
    "2": "3",
    "3": "4"
};
var arr = [];
for (var prop in data) {
    arr.push(data[prop]);
}
console.log(arr);

DEMO

share|improve this answer
add comment
var JsonObj= {"0":"1","1":"2","2":"3","3":"4"};
var array = [];
for(var i in JsonObj) {
    if(JsonObj.hasOwnProperty(i) && !isNaN(+i)) {
        array[+i] = JsonObj[i];
    }
}

DEMO

share|improve this answer
add comment

Try this:

var newArr = [];
$.each(JSONObject.results.bindings, function(i, obj) {
    newArr.push([obj.value]);
});
share|improve this answer
add comment

Should be easy with jQuery

var arr = $.map(obj, function(el) { return el; });

FIDDLE

assuming it's already parsed as an object, and isn't actually JSON

share|improve this answer
 
fiddle is not working.. –  Nikhil Agrawal Jan 2 at 11:02
 
@NikhilAgrawal - works just fine for me? –  adeneo Jan 2 at 11:02
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.