439

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?

4
  • 1
    Should the array indices be the same as keys in original object? First index in an array is always 0, but your own code and most answers (including the accepted one) seem to ignore it; still, you've reverted my edit to desired example result.
    – Imre
    Commented Sep 12, 2014 at 10:45
  • 1
    Yes, you are right: first Array element starts with 0. But I reverted your edit, because it was not consistent in my eyes to keep that example simple as possible, because changing myObj= {1:[Array-Data] to myObj= {0:[Array-Data] was not part of your edit (as I remember right)
    – The Bndr
    Commented Sep 17, 2014 at 12:40
  • 3
    Use the jQuery $.makeArray(obj) command for that api.jquery.com/jQuery.makeArray
    – DevlshOne
    Commented Mar 12, 2015 at 16:38
  • @DevlshOne the documentation u provided says: "Turn a jQuery object into an array" i dont think this fits on OP question
    – Alex
    Commented Nov 7, 2018 at 9:05

18 Answers 18

763

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)
6
  • 10
  • 3
    Unsatisfied with the top answer, I just wrote this almost exact function, came back to post it as an answer, scrolled down, saw 170. Realized, man If I hadn't given up I wouldn't have had to think :) This should be at the top. OP pls select as answer.
    – j03m
    Commented Apr 6, 2016 at 19:27
  • 1
    for anyone for whom this is not obvious, the keys don't need to be sequential (i.e. in this example they are 1 and 2 - but they could just as well be a string key or non sequential number Commented May 31, 2016 at 2:41
  • For the first paragraph of code I get missing semi-colon. Not sure why. Commented Aug 14, 2016 at 15:52
  • @JohnnyBizzle I guess your linter requires to write "return obj[key];" with a semicolon in the end. JavaScript does not though.
    – Joel
    Commented Aug 16, 2016 at 9:06
448
var myObj = {
    1: [1, 2, 3],
    2: [4, 5, 6]
};

var array = $.map(myObj, function(value, index) {
    return [value];
});


console.log(array);

Output:

[[1, 2, 3], [4, 5, 6]]
14
  • 9
    @Dogbert, please could you explain the $.map? Every search I try to do on this just turns up lots of links to jQuery or the map method of arrays.
    – crantok
    Commented Feb 4, 2014 at 15:57
  • 22
    D'oh! Ignore my comment. I hadn't noticed the jQuery tag on this question.
    – crantok
    Commented Feb 4, 2014 at 16:04
  • 8
    is there a way to maintain the keys in the new array? every answer on the www i see lacks the conversion of keys.
    – Nijboer IT
    Commented Apr 9, 2014 at 11:59
  • 55
    You can also do this without jQuery: Object.keys(myObject).map(function(val) { return [val] }); Commented Sep 30, 2014 at 19:04
  • 3
    @TD_Nijboer Yes, use value.key = index; return [value]; instead of return [value]; Commented Nov 5, 2014 at 18:38
34

Simply do

Object.values(obj);

That's all!

3
  • 12
    Object.values is an ES2017 method that is not supported in Safari, IE, Node 6. Commented Jun 5, 2017 at 15:48
  • Object.values is supported in Safari 10.1+, Node 7+
    – The Bndr
    Commented Dec 15, 2022 at 13:25
  • I would prefer people to read other answers before posting. Joel's answer already contained this info (with more detail) on Mar 11, 2016 -- nearly a year before this was posted. This sort of an answer, as with several below, don't add anything that isn't already here & just make it harder to find actual varied replies. IDK if this is just intentional reputation farming, or if people regularly neglect due diligence when writing answers. Commented Mar 27 at 13:26
30

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]);
        }
    }
}
8
  • 1
    You should have tested the code. $.map will flatten Array-Data. Commented Jul 28, 2011 at 10:35
  • 1
    you are right i didn't test it with an array and map flattens it! i modified the answer Commented Jul 28, 2011 at 10:42
  • @Nicola Peluchetti $.makeArray() sounds good, but is not what I was looking for, because it simply puts the object to an array element: [{1:[Array-Data], 2:[Array-Data]}] And $.map() also doesn't look successful. It seams, that all Sub-Array data is merged to one array. array.length should return 2 (because 2 elements exists), but it returns 67 which is the number of all elements in all ["Array-Data"].
    – The Bndr
    Commented Jul 28, 2011 at 10:45
  • @The Bndr i posted another solution, but you can use map as suggested by dogbert Commented Jul 28, 2011 at 10:46
  • I think you must explicitly specify the array index... like arr[+i] = myObj[i]; because (i) for(...in...) is not guaranteed to return properties in any order (ii) in OP's example the properties start from 1, not 0. Commented Jul 28, 2011 at 10:58
25

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

var myObj = {
    1: ['c', 'd'],
    2: ['a', 'b']
  },
  myArr;

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

2
  • 1
    It would be far better for the code that is generating the object to also set the length or indeed make it an array in the first place. I don't expect either are possible, so this answer for me isn't helpful. Commented Nov 8, 2013 at 11:58
  • myObj.length = Object.keys(myObj).length
    – baldrs
    Commented Dec 22, 2016 at 10:18
19

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]);
1
  • 1
    For the current ES5 (although I do enjoy ES6): Object.keys(yourObject).map(function(key){ return yourObject[key] }); Commented Feb 18, 2015 at 2:51
18

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

2
  • if i do something like var state = { ingredient: { salad: 1, bacon: 1, } } and then var HariOm = Object.values(state); followed by console.log(typeof HariOM) it displays the type as an object. Shouldn't it display it as an array?
    – Alwaysblue
    Commented May 27, 2018 at 21:07
  • That's completely normal, check the reference here : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - You can use Array.isArray(HariOM)
    – Stopi
    Commented Aug 7, 2018 at 13:59
17

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

var myArr = Array.prototype.slice.call(myObj, 0);
3
  • @Qwerty which browser?
    – test30
    Commented Jul 16, 2014 at 8:47
  • Chrome. Tested with var myObj = {1:[1,2,3],2:[4,5,6]};
    – Qwerty
    Commented Aug 1, 2014 at 13:17
  • Note that this method works for converting "array-like objects", meaning they've got to have a "length" property and enumerated properties counting up from 0. So, to make @Qwerty's example work try this: {0:[1,2,3], 1:[4,5,6], length:2}. Experiment with index values and length values, it's a little lenient. Here's a good read on the topic: nfriedly.com/techblog/2009/06/… Skip down to "Array-like Objects".
    – Matt
    Commented Apr 14, 2015 at 0:36
15
x = [];
for( var i in myObj ) {
    x[i] = myObj[i];
}
2
  • 10
    You should use push, otherwise you might end up creating an object Commented Jul 28, 2011 at 10:44
  • Maybe It is some better force to int the index. var bbb = {'1': 'a', '3': 'b'}; var x = []; for (var i in bbb) { x[parseInt(i)] = bbb[i];} console.log(x);
    – tres.14159
    Commented Feb 19, 2016 at 16:32
15

ECMASCRIPT 5:

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

ECMASCRIPT 2015 or ES6:

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

How about jQuery.makeArray(obj)

This is how I did it in my app.

2
  • 2
    This returns [Object] for the above example. Commented Sep 30, 2014 at 19:00
  • 1
    just a matter of adding [0] index and you saved my life :)
    – Raheel
    Commented Mar 24, 2015 at 13:54
7

ES8 way made easy:

The official documentation

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

6

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

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

1
  • I might be wrong, but should it be better for myObj to be an enumerable starting at 0 ? Else what, it seems to me that there we have an issues where our Array would be : [undefined,[1,[2],3]] (The first part is undefined because it don't find myObj['0'] and the last part myObj['2'] being ejected because after reading .length it stop at myObj['1']? Commented Sep 19, 2016 at 12:37
2

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.

1

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

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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.