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. 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) Commented Sep 17, 2014 at 12:40
  • 3
    Use the jQuery $.makeArray(obj) command for that api.jquery.com/jQuery.makeArray 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 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)
Sign up to request clarification or add additional context in comments.

6 Comments

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.
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
For the first paragraph of code I get missing semi-colon. Not sure why.
@JohnnyBizzle I guess your linter requires to write "return obj[key];" with a semicolon in the end. JavaScript does not though.
|
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 Comments

@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.
D'oh! Ignore my comment. I hadn't noticed the jQuery tag on this question.
is there a way to maintain the keys in the new array? every answer on the www i see lacks the conversion of keys.
You can also do this without jQuery: Object.keys(myObject).map(function(val) { return [val] });
@TD_Nijboer Yes, use value.key = index; return [value]; instead of return [value];
|
34

Simply do

Object.values(obj);

That's all!

3 Comments

Object.values is an ES2017 method that is not supported in Safari, IE, Node 6.
Object.values is supported in Safari 10.1+, Node 7+
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.
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 Comments

You should have tested the code. $.map will flatten Array-Data.
you are right i didn't test it with an array and map flattens it! i modified the answer
@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 i posted another solution, but you can use map as suggested by dogbert
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.
|
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 Comments

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.
myObj.length = Object.keys(myObj).length
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 Comment

For the current ES5 (although I do enjoy ES6): Object.keys(yourObject).map(function(key){ return yourObject[key] });
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 Comments

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?
That's completely normal, check the reference here : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - You can use Array.isArray(HariOM)
17

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

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

3 Comments

@Qwerty which browser?
Chrome. Tested with var myObj = {1:[1,2,3],2:[4,5,6]};
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".
15
x = [];
for( var i in myObj ) {
    x[i] = myObj[i];
}

2 Comments

You should use push, otherwise you might end up creating an object
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);
15

ECMASCRIPT 5:

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

ECMASCRIPT 2015 or ES6:

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

Comments

13

How about jQuery.makeArray(obj)

This is how I did it in my app.

2 Comments

This returns [Object] for the above example.
just a matter of adding [0] index and you saved my life :)
7

ES8 way made easy:

The official documentation

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

Comments

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

Comments

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 Comment

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']?
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.

Comments

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

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.