I have a JSON object like this coming back as a server response:

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

I want to convert it into JavaScript array like:

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

Is there a best way to do this? Wherever I am reading, people are using complex logic using loops. So are there alternative methods to doing this?

share|improve this question
3  
duplicate : stackoverflow.com/questions/6857468/… – pbenard Jan 2 '14 at 10:55
5  
A mere loop is no complex logic, by the way : )) – moonwave99 Jul 20 '15 at 8:37

13 Answers 13

up vote 248 down vote accepted

It's actually very straight forward with jQuery's $.map

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

FIDDLE

and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with Array.map

var arr = Object.keys(obj).map(function(k) { return obj[k] });

FIDDLE

That's assuming it's already parsed as a javascript object, and isn't actually JSON, which is a string format, in that case a run through JSON.parse would be necessary as well.

In ES2015 there's Object.values to the rescue, which makes this a breeze

var arr = Object.values(obj);
share|improve this answer
5  
fiddle is not working.. – Nikhil Agrawal Jan 2 '14 at 11:02
    
@NikhilAgrawal - works just fine for me? – adeneo Jan 2 '14 at 11:02
    
Works for me.. thank you :) – Rafique Mohammed Aug 28 '14 at 6:23
1  
@adeneo Sir can you please provide some explanation about htis methods. – Nikhil Agrawal Nov 27 '14 at 7:53
1  
@adeneo aka Mr. burns... Thanks for this quick solution. – Dzeimsas Zvirblis Jun 19 '15 at 20:59
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
    
thanks. really needed that. someone used an object as an array throughout a ton of code, which was fine until i needed to build on top of it... – amanda fouts Dec 13 '15 at 6:27
    
Thank you! Perfect answer. – Vincent Dec 18 '15 at 21:32
    
very close to what I needed thanks: for(var x in data){ arr[x] = data[x]; } – Andrew Jan 11 at 20:49

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
1  
Thanks - works like charm. But how to make it do the same for internal objects also (objects within objects)? Internal objects should also become flat members of the array at the root level (so that they can be passed to, say, datatables.net etc.) – Gopalakrishna Palem Dec 18 '14 at 10:04

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

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
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

Try this:

var newArr = [];
$.each(JSONObject.results.bindings, function(i, obj) {
    newArr.push([obj.value]);
});
share|improve this answer
    
Your solution is going to be the slowest one from all presented here... Bad for business code ;) – HellBaby Mar 1 '16 at 14:11

Not sure what I am missing here but simply trying the below code does the work. Am I missing anything here?

https://jsfiddle.net/vatsalpande/w3ew5bhq/

$(document).ready(function(){

var json = {
   "code" :"1", 
   "data" : { 
    "0" : {"id":"1","score":"44"},
    "1" : {"id":"1","score":"44"}
    }
  };

  createUpdatedJson();

  function createUpdatedJson(){

    var updatedJson = json;

    updatedJson.data = [updatedJson.data];

    $('#jsondata').html(JSON.stringify(updatedJson));


    console.log(JSON.stringify(updatedJson));
  }
 })
share|improve this answer

Assuming your have a value like the following

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

Then you can turn this into a javascript array using the following

var arr = [];
json = JSON.stringify(eval('(' + obj + ')')); //convert to json string
arr = $.parseJSON(json); //convert to javascript array

This works for converting json into multi-diminsional javascript arrays as well.

None of the other methods on this page seemed to work completely for me when working with php json-encoded strings except the method I am mentioning herein.

share|improve this answer

Using raw javascript, suppose you have:

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

You could get the values with:

Object.keys(j).map(function(_) { return j[_]; })

Output:

["1", "2", "3", "4"]
share|improve this answer

Here is an example of how you could get an array of objects and then sort the array.

  function osort(obj)
  {  // map the object to an array [key, obj[key]]
    return Object.keys(obj).map(function(key) { return [key, obj[key]] }).sort(
      function (keya, keyb)
      { // sort(from largest to smallest)
          return keyb[1] - keya[1];
      }
    );
  }
share|improve this answer

This is best solution. I think so.

Object.keys(obj).map(function(k){return {key: k, value: obj[k]}})
share|improve this answer
var obj=  {"0":"1", "1":"2", "2":"3", "3":"4"};
var arr = [];
var keys = window.jQuery.map(obj, function(value, key) {
  arr.splice(key, 0, value); 
  console.log(arr);
});
share|improve this answer
    
Doesn't seem to work: jsfiddle.net/bb5asme7 Uncaught TypeError: obj.toJSON is not a function – Dr. Gianluigi Zane Zanettini Jan 16 '16 at 11:35
    
I have changed the code....please try this – VAYU Feb 5 '16 at 12:47

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.