[javascript] 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?

This question is related to javascript jquery arrays json javascript-objects

The answer is


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/


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

_x000D_
_x000D_
var JsonObj = {_x000D_
  "0": "1",_x000D_
  "1": "2",_x000D_
  "2": "3",_x000D_
  "3": "4"_x000D_
};_x000D_
_x000D_
var array = [];_x000D_
for (var i in JsonObj) {_x000D_
  if (JsonObj.hasOwnProperty(i) && !isNaN(+i)) {_x000D_
    array[+i] = JsonObj[i];_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log(array)
_x000D_
_x000D_
_x000D_

DEMO


      var data = [];

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

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

Try this:

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

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

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

This is best solution. I think so.

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

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


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!


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

_x000D_
_x000D_
const input = {_x000D_
  "0": "1",_x000D_
  "1": "2",_x000D_
  "2": "3",_x000D_
  "3": "4"_x000D_
}_x000D_
_x000D_
const output = Object.assign([], input)_x000D_
_x000D_
console.log(output)
_x000D_
_x000D_
_x000D_

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.


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.


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

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to javascript-objects

Cannot read property 'style' of undefined -- Uncaught Type Error Is this a good way to clone an object in ES6? What’s the difference between “{}” and “[]” while declaring a JavaScript array? Comparing two arrays of objects, and exclude the elements who match values into new array in JS Converting JavaScript object with numeric keys into array From an array of objects, extract value of a property as array How to copy JavaScript object to new variable NOT by reference? Remove property for all objects in array Using curl POST with variables defined in bash script functions How to sum the values of a JavaScript object?