Nikhil Agrawal
Nikhil Agrawal

Reputation: 26528

Converting JavaScript object with numeric keys into array

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?

Upvotes: 184

Views: 680765

Answers (17)

adeneo
adeneo

Reputation: 318182

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

const o = {"0":"1","1":"2","2":"3","3":"4"};
const arr = $.map(o, function(el) { return el; })
console.log(arr)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

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

const o = {"0":"1","1":"2","2":"3","3":"4"};
const arr = Object.keys(o).map(k => o[k]);
console.log(arr)

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, but only if your object doesn't have any gaps in the keys:

const o = {"0":"1","1":"2","2":"3","3":"4"};
const arr = Object.values(o);
console.log(arr);

If there are gaps, you'll want to use Object.entires instead, and then reduce the key/value pairs to an array instead:

const o = {"0":"1","5":"6","7":"8","10":"11"};
const arr = Object.entries(o).reduce((arr, [key, value]) => {
  arr[key] = value;
  return arr;
}, []);
console.log(arr);

Upvotes: 331

informatik-handwerk.de
informatik-handwerk.de

Reputation: 303

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

Upvotes: 1

ASM
ASM

Reputation: 169

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

Upvotes: 4

Satpal
Satpal

Reputation: 133403

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

Upvotes: 24

benhowdle89
benhowdle89

Reputation: 37464

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!

Upvotes: 107

Tareq Salah
Tareq Salah

Reputation: 3718

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

Upvotes: 9

adiga
adiga

Reputation: 35222

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.

Upvotes: 6

Manav Akela
Manav Akela

Reputation: 174

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

Upvotes: -1

cz game
cz game

Reputation: 81

      var data = [];

      data  = {{ jdata|safe }}; //parse through js
      var i = 0 ;
      for (i=0;i<data.length;i++){
         data[i] = data[i].value;
      }

Upvotes: -1

tutaro
tutaro

Reputation: 29

This is best solution. I think so.

Object.keys(obj).map(function(k){return {key: k, value: obj[k]}})

Upvotes: 0

Vatsal
Vatsal

Reputation: 2128

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

Upvotes: 2

Asher
Asher

Reputation: 2774

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

Upvotes: 1

mvallebr
mvallebr

Reputation: 2508

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

Upvotes: 2

skidadon
skidadon

Reputation: 547

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.

Upvotes: 1

deviloper
deviloper

Reputation: 7240

Try this:

var newArr = [];
$.each(JSONObject.results.bindings, function(i, obj) {
    newArr.push([obj.value]);
});

Upvotes: 4

moonwave99
moonwave99

Reputation: 22817

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();

Upvotes: 20

Yabada
Yabada

Reputation: 1758

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/

Upvotes: 9

Related Questions