181

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

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

I want to convert it into a JavaScript array like this:

["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?

adiga
  • 34,372
  • 9
  • 61
  • 83
Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126

17 Answers17

331

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);
computingfreak
  • 4,939
  • 1
  • 34
  • 51
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 1
    @adeneo Sir can you please provide some explanation about htis methods. – Nikhil Agrawal Nov 27 '14 at 07:53
  • 1
    @adeneo aka Mr. burns... Thanks for this quick solution. – Dzeimsas Zvirblis Jun 19 '15 at 20:59
  • 1
    @NikhilAgrawal The trick here is to use Object.keys(), which returns the keys of the object (= its own enumerable properties) *as an array*. Then we can use array.map to replace each key by the corresponding value in a new array. – antoine Jun 19 '15 at 22:12
  • 1
    This is an answer, but not a very friendly one. – sheriffderek Sep 20 '15 at 19:39
  • Don't you need to sort the result of Object.keys first? I believe JS does not guarantee any property order. – leejt489 Oct 08 '15 at 00:17
  • @leejt489 - there is no order in objects, just as there is no order mentioned in the question, it's just a question of how to return the objects values instead of the keys, as an array. – adeneo Oct 08 '15 at 02:59
  • And sorting the keys does not necessarily sort the array of values – adeneo Oct 08 '15 at 03:05
  • 3
    The question wasn't explicit, but I had assumed that the keys of the object are indexes of the array by nature of them being (0,1,2,3). Just pointing out that people should know that this method doesn't guarantee any order in the array; if the keys are indexes then you need to explicitly order them so the array is built in the correct order. – leejt489 Oct 09 '15 at 17:37
  • @leejt489 - maybe you're right, and maybe you're wrong. The OP is asking for a solution on how to get the values from the object into an array, and as there is no order in objects, there is no order in the array either. If the object was something like `{"0":"2", "1":"1", "2":"5", "3":"1"}`, what would you expect the result to be, `["2", "1", "5", "1"]` or `["1", "1", "2", "5"]` ? There's really no expection of order here, it's all just an opinion, and the OP doesn't specify anything other than just getting the values, not the keys. – adeneo Oct 09 '15 at 18:34
  • If the server responds with `{"0":"0","2":"2","1":"1"}` and you read it as `["0","2","1"]` instead of `["0","1","2"]` then it is most certainly a bug, I don't see any ambiguity here. – riv Nov 30 '20 at 16:55
  • The answer is correct only under stronger assumptions than stated in the question. Those proposed solutions will produce an array with indexes starting from 0 and continuously upwards. Hover the actual keys might "just be numeric", start anywhere and contain holes. – informatik-handwerk.de Dec 11 '21 at 17:56
108

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]);
}

console.log(arr)

Hope this is what you're after!

adiga
  • 34,372
  • 9
  • 61
  • 83
benhowdle89
  • 36,900
  • 69
  • 202
  • 331
  • 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 06:27
  • very close to what I needed thanks: for(var x in data){ arr[x] = data[x]; } – Andrew Jan 11 '17 at 20:49
24

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

adiga
  • 34,372
  • 9
  • 61
  • 83
Satpal
  • 132,252
  • 13
  • 159
  • 168
20

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();
moonwave99
  • 21,957
  • 3
  • 43
  • 64
  • 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
  • +1: "There is nothing like a "JSON object" - JSON is a serialization notation." - I can't believe how many times I had to hear this before fully understand it. – radbyx Nov 10 '17 at 07:25
9

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/

Yabada
  • 1,728
  • 1
  • 15
  • 36
9

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];
  }
}

console.log(array)

DEMO

adiga
  • 34,372
  • 9
  • 61
  • 83
Tareq Salah
  • 3,720
  • 4
  • 34
  • 48
5

You can use Object.assign() with an empty array literal [] as the target:

const input = {
  "0": "1",
  "1": "2",
  "2": "3",
  "3": "4"
}

const output = Object.assign([], input)

console.log(output)

If you check the polyfill, Object.assign(target, ...sources) just copies all the enumerable own properties from the source objects to a target object. If the target is an array, it will add the numerical keys to the array literal and return that target array object.

adiga
  • 34,372
  • 9
  • 61
  • 83
4

Try this:

var newArr = [];
$.each(JSONObject.results.bindings, function(i, obj) {
    newArr.push([obj.value]);
});
M Reza Saberi
  • 7,134
  • 9
  • 47
  • 76
4

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

var vals = Object.values(obj);

console.log(vals); //["1", "2", "3", "4"]

Another alternative to the question

var vals = Object.values(JSON.parse(obj)); //where json needs to be parsed
adiga
  • 34,372
  • 9
  • 61
  • 83
ASM
  • 169
  • 3
  • 12
2

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"]
mvallebr
  • 2,388
  • 21
  • 36
2

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));
  }
 })
Vatsal
  • 2,068
  • 4
  • 21
  • 24
1

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.

skidadon
  • 547
  • 4
  • 7
1

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];
      }
    );
  }
Asher
  • 2,638
  • 6
  • 31
  • 41
1

The accepted solution expects the keys start from 0 and are continuous - it gets the values into the array, but looses the indexes on the way.

Use this if your "object with numerical keys" does not fulfill those stricter assumptions.

//let sourceObject = ...
let destinationArray = [];
Object.keys(sourceObject).forEach(k => destinationArray[k] = sourceObject[k]);
0

This is best solution. I think so.

Object.keys(obj).map(function(k){return {key: k, value: obj[k]}})
tutaro
  • 29
  • 1
-1
      var data = [];

      data  = {{ jdata|safe }}; //parse through js
      var i = 0 ;
      for (i=0;i<data.length;i++){
         data[i] = data[i].value;
      }
cz game
  • 81
  • 1
  • 5
  • 3
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation would greatly improve its long-term value](//meta.stackexchange.com/q/114762/206345) by showing _why_ this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – Mogsdad Dec 31 '17 at 20:39
-1

You can convert json Object into Array & String using PHP.

$data='{"resultList":[{"id":"1839","displayName":"Analytics","subLine":""},{"id":"1015","displayName":"Automation","subLine":""},{"id":"1084","displayName":"Aviation","subLine":""},{"id":"554","displayName":"Apparel","subLine":""},{"id":"875","displayName":"Aerospace","subLine":""},{"id":"1990","displayName":"Account Reconciliation","subLine":""},{"id":"3657","displayName":"Android","subLine":""},{"id":"1262","displayName":"Apache","subLine":""},{"id":"1440","displayName":"Acting","subLine":""},{"id":"710","displayName":"Aircraft","subLine":""},{"id":"12187","displayName":"AAC","subLine":""}, {"id":"20365","displayName":"AAT","subLine":""}, {"id":"7849","displayName":"AAP","subLine":""}, {"id":"20511","displayName":"AACR2","subLine":""}, {"id":"28585","displayName":"AASHTO","subLine":""}, {"id":"45191","displayName":"AAMS","subLine":""}]}';

$b=json_decode($data);

$i=0;
while($b->{'resultList'}[$i])
{
    print_r($b->{'resultList'}[$i]->{'displayName'});
    echo "<br />";
    $i++;
}
Manav Akela
  • 166
  • 2