[javascript] Converting a JS object to an array using jQuery

My application creates a JavaScript object, like the following:

myObj= {1:[Array-Data], 2:[Array-Data]}

But I need this object as an array.

array[1]:[Array-Data]
array[2]:[Array-Data]

So I tried to convert this object to an array by iterating with $.each through the object and adding the element to an array:

x=[]
$.each(myObj, function(i,n) {
    x.push(n);});

Is there an better way to convert an object to an array or maybe a function?

This question is related to javascript jquery arrays object

The answer is


The best method would be using a javascript -only function:

var myArr = Array.prototype.slice.call(myObj, 0);

I think you can use for in but checking if the property is not inerithed

myObj= {1:[Array-Data], 2:[Array-Data]}
var arr =[];
for( var i in myObj ) {
    if (myObj.hasOwnProperty(i)){
       arr.push(myObj[i]);
    }
}

EDIT - if you want you could also keep the indexes of your object, but you have to check if they are numeric (and you get undefined values for missing indexes:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

myObj= {1:[1,2], 2:[3,4]}
var arr =[];
for( var i in myObj ) {
    if (myObj.hasOwnProperty(i)){
        if (isNumber(i)){
            arr[i] = myObj[i];
        }else{
          arr.push(myObj[i]);
        }
    }
}

You can create a simple function to do the conversion from object to array, something like this can do the job for you using pure javascript:

var objectToArray = function(obj) {
  var arr = [];
  if ('object' !== typeof obj || 'undefined' === typeof obj || Array.isArray(obj)) {
    return obj;
  } else {
    Object.keys(obj).map(x=>arr.push(obj[x]));
  }
  return arr;
};

or this one:

var objectToArray = function(obj) {
  var arr =[];
  for(let o in obj) {
    if (obj.hasOwnProperty(o)) {
      arr.push(obj[o]);
    }
  }
  return arr;
};

and call and use the function as below:

var obj = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'};
objectToArray(obj); // return ["a", "b", "c", "d", "e"]

Also in the future we will have something called Object.values(obj), similar to Object.keys(obj) which will return all properties for you as an array, but not supported in many browsers yet...


I made a custom function:

    Object.prototype.toArray=function(){
    var arr=new Array();
    for( var i in this ) {
        if (this.hasOwnProperty(i)){
            arr.push(this[i]);
        }
    }
    return arr;
};

If you know the maximum index in you object you can do the following:

_x000D_
_x000D_
var myObj = {_x000D_
    1: ['c', 'd'],_x000D_
    2: ['a', 'b']_x000D_
  },_x000D_
  myArr;_x000D_
_x000D_
myObj.length = 3; //max index + 1_x000D_
myArr = Array.prototype.slice.apply(myObj);_x000D_
console.log(myArr); //[undefined, ['c', 'd'], ['a', 'b']]
_x000D_
_x000D_
_x000D_


Fiddle Demo

Extension to answer of bjornd .

var myObj = {
    1: [1, [2], 3],
    2: [4, 5, [6]]
}, count = 0,
    i;
//count the JavaScript object length supporting IE < 9 also
for (i in myObj) {
    if (myObj.hasOwnProperty(i)) {
        count++;
    }
}
//count = Object.keys(myObj).length;// but not support IE < 9
myObj.length = count + 1; //max index + 1
myArr = Array.prototype.slice.apply(myObj);
console.log(myArr);


Reference

Array.prototype.slice()

Function.prototype.apply()

Object.prototype.hasOwnProperty()

Object.keys()


After some tests, here is a general object to array function convertor:

You have the object:

var obj = {
    some_key_1: "some_value_1"
    some_key_2: "some_value_2"
};

The function:

function ObjectToArray(o)
{
    var k = Object.getOwnPropertyNames(o);
    var v = Object.values(o);

    var c = function(l)
    {
        this.k = [];
        this.v = [];
        this.length = l;
    };

    var r = new c(k.length);

    for (var i = 0; i < k.length; i++)
    {
        r.k[i] = k[i];
        r.v[i] = v[i];
    }

    return r;
}

Function Use:

var arr = ObjectToArray(obj);

You Get:

arr {
    key: [
        "some_key_1",
        "some_key_2"
    ],
    value: [
        "some_value_1",
        "some_value_2"
    ],
    length: 2
}

So then you can reach all keys & values like:

for (var i = 0; i < arr.length; i++)
{
    console.log(arr.key[i] + " = " + arr.value[i]);
}

Result in console:

some_key_1 = some_value_1
some_key_2 = some_value_2

Edit:

Or in prototype form:

Object.prototype.objectToArray = function()
{
    if (
        typeof this != 'object' ||
        typeof this.length != "undefined"
    ) {
        return false;
    }

    var k = Object.getOwnPropertyNames(this);
    var v = Object.values(this);

    var c = function(l)
    {
        this.k = [];
        this.v = [];
        this.length = l;
    };

    var r = new c(k.length);

    for (var i = 0; i < k.length; i++)
    {
        r.k[i] = k[i];
        r.v[i] = v[i];
    }

    return r;
};

And then use like:

console.log(obj.objectToArray);

The solving is very simple

var my_obj = {1:[Array-Data], 2:[Array-Data]}
Object.keys(my_obj).map(function(property_name){ 
    return my_obj[property_name]; 
});

Nowadays, there is a simple way to do this : Object.values().

var myObj = {
    1: [1, 2, 3],
    2: [4, 5, 6]
};

console.log(Object.values(myObj));

Output:

[[1, 2, 3], [4, 5, 6]]

This doesn't required jQuery, it's been defined in ECMAScript 2017.
It's supported by every modern browser (forget IE).


ES8 way made easy:

The official documentation

_x000D_
_x000D_
    const obj = { x: 'xxx', y: 1 };_x000D_
    let arr = Object.values(obj); // ['xxx', 1]_x000D_
    console.log(arr);
_x000D_
_x000D_
_x000D_


If you want to keep the name of the object's properties as values. Example:

var fields = {
    Name: { type: 'string', maxLength: 50 },
    Age: { type: 'number', minValue: 0 }
}

Use Object.keys(), Array.map() and Object.assign():

var columns = Object.keys( fields ).map( p => Object.assign( fields[p], {field:p} ) )

Result:

[ { field: 'Name', type: 'string', maxLength: 50 }, 
  { field: 'Age', type: 'number', minValue: 0 } ]

Explanation:

Object.keys() enumerates all the properties of the source ; .map() applies the => function to each property and returns an Array ; Object.assign() merges name and value for each property.


How about jQuery.makeArray(obj)

This is how I did it in my app.


x = [];
for( var i in myObj ) {
    x[i] = myObj[i];
}

If you are looking for a functional approach:

var obj = {1: 11, 2: 22};
var arr = Object.keys(obj).map(function (key) { return obj[key]; });

Results in:

[11, 22]

The same with an ES6 arrow function:

Object.keys(obj).map(key => obj[key])

With ES7 you will be able to use Object.values instead (more information):

var arr = Object.values(obj);

Or if you are already using Underscore/Lo-Dash:

var arr = _.values(obj)

Simply do

Object.values(obj);

That's all!


Since ES5 Object.keys() returns an array containing the properties defined directly on an object (excluding properties defined in the prototype chain):

Object.keys(yourObject).map(function(key){ return yourObject[key] });

ES6 takes it one step further with arrow functions:

Object.keys(yourObject).map(key => yourObject[key]);

ECMASCRIPT 5:

Object.keys(myObj).map(function(x) { return myObj[x]; })

ECMASCRIPT 2015 or ES6:

Object.keys(myObj).map(x => myObj[x])

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 object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor