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?
javascript jquery arrays object
add a comment |
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?
javascript jquery arrays object
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
Sep 12 '14 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 changingmyObj= {1:[Array-Data]tomyObj= {0:[Array-Data]was not part of your edit (as I remember right)
– The Bndr
Sep 17 '14 at 12:40
3
Use the jQuery $.makeArray(obj) command for that api.jquery.com/jQuery.makeArray
– DevlshOne
Mar 12 '15 at 16:38
@DevlshOne the documentation u provided says: "Turn a jQuery object into an array" i dont think this fits on OP question
– AXL
Nov 7 '18 at 9:05
add a comment |
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?
javascript jquery arrays object
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?
javascript jquery arrays object
javascript jquery arrays object
edited Sep 12 '17 at 14:09
Anthony Johnston
7,13543450
7,13543450
asked Jul 28 '11 at 10:26
The BndrThe Bndr
7,630124687
7,630124687
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
Sep 12 '14 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 changingmyObj= {1:[Array-Data]tomyObj= {0:[Array-Data]was not part of your edit (as I remember right)
– The Bndr
Sep 17 '14 at 12:40
3
Use the jQuery $.makeArray(obj) command for that api.jquery.com/jQuery.makeArray
– DevlshOne
Mar 12 '15 at 16:38
@DevlshOne the documentation u provided says: "Turn a jQuery object into an array" i dont think this fits on OP question
– AXL
Nov 7 '18 at 9:05
add a comment |
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
Sep 12 '14 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 changingmyObj= {1:[Array-Data]tomyObj= {0:[Array-Data]was not part of your edit (as I remember right)
– The Bndr
Sep 17 '14 at 12:40
3
Use the jQuery $.makeArray(obj) command for that api.jquery.com/jQuery.makeArray
– DevlshOne
Mar 12 '15 at 16:38
@DevlshOne the documentation u provided says: "Turn a jQuery object into an array" i dont think this fits on OP question
– AXL
Nov 7 '18 at 9:05
1
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
Sep 12 '14 at 10:45
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
Sep 12 '14 at 10:45
1
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
Sep 17 '14 at 12:40
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
Sep 17 '14 at 12:40
3
3
Use the jQuery $.makeArray(obj) command for that api.jquery.com/jQuery.makeArray
– DevlshOne
Mar 12 '15 at 16:38
Use the jQuery $.makeArray(obj) command for that api.jquery.com/jQuery.makeArray
– DevlshOne
Mar 12 '15 at 16:38
@DevlshOne the documentation u provided says: "Turn a jQuery object into an array" i dont think this fits on OP question
– AXL
Nov 7 '18 at 9:05
@DevlshOne the documentation u provided says: "Turn a jQuery object into an array" i dont think this fits on OP question
– AXL
Nov 7 '18 at 9:05
add a comment |
18 Answers
18
active
oldest
votes
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]]
7
@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
Feb 4 '14 at 15:57
20
D'oh! Ignore my comment. I hadn't noticed the jQuery tag on this question.
– crantok
Feb 4 '14 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.
– TD_Nijboer
Apr 9 '14 at 11:59
52
You can also do this without jQuery: Object.keys(myObject).map(function(val) { return [val] });
– Kris Erickson
Sep 30 '14 at 19:04
3
@TD_Nijboer Yes, usevalue.key = index; return [value];instead ofreturn [value];
– Simon Arnold
Nov 5 '14 at 18:38
|
show 16 more comments
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)
3
Lodash docs say "iteration order is not guaranteed" though
– Karel Bílek
Mar 31 '15 at 18:51
9
@KarelBílek Is iteration order for a JS object ever guaranteed? 'An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function.'
– Meshaal
May 28 '15 at 1:35
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
Apr 6 '16 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
– Simon_Weaver
May 31 '16 at 2:41
For the first paragraph of code I get missing semi-colon. Not sure why.
– JohnnyBizzle
Aug 14 '16 at 15:52
|
show 5 more comments
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]);
}
}
}
1
You should have tested the code.$.mapwill flattenArray-Data.
– Marko Dumic
Jul 28 '11 at 10:35
you are right i didn't test it with an array and map flattens it! i modified the answer
– Nicola Peluchetti
Jul 28 '11 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.lengthshould return 2 (because 2 elements exists), but it returns 67 which is the number of all elements in all ["Array-Data"].
– The Bndr
Jul 28 '11 at 10:45
@The Bndr i posted another solution, but you can use map as suggested by dogbert
– Nicola Peluchetti
Jul 28 '11 at 10:46
I think you must explicitly specify the array index... likearr[+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.
– Salman A
Jul 28 '11 at 10:58
|
show 4 more comments
Simply do
Object.values(obj);
That's all!
11
Object.values is an ES2017 method that is not supported in Safari, IE, Node 6.
– Phil Ricketts
Jun 5 '17 at 15:48
add a comment |
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']]
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.
– user2000095-tim
Nov 8 '13 at 11:58
myObj.length = Object.keys(myObj).length
– baldrs
Dec 22 '16 at 10:18
add a comment |
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
For the current ES5 (although I do enjoy ES6): Object.keys(yourObject).map(function(key){ return yourObject[key] });
– Macmee
Feb 18 '15 at 2:51
add a comment |
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).
if i do something likevar state = { ingredient: { salad: 1, bacon: 1, } }and thenvar HariOm = Object.values(state);followed byconsole.log(typeof HariOM)it displays the type as an object. Shouldn't it display it as an array?
– NoobieSatan
May 27 '18 at 21:07
That's completely normal, check the reference here : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - You can useArray.isArray(HariOM)
– Stopi
Aug 7 '18 at 13:59
add a comment |
x = ;
for( var i in myObj ) {
x[i] = myObj[i];
}
10
You should use push, otherwise you might end up creating an object
– Nicola Peluchetti
Jul 28 '11 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
Feb 19 '16 at 16:32
add a comment |
The best method would be using a javascript -only function:
var myArr = Array.prototype.slice.call(myObj, 0);
4
This doesn't seem to work for me..:-/
– Qwerty
Jul 3 '14 at 10:37
@Qwerty which browser?
– test30
Jul 16 '14 at 8:47
Chrome. Tested withvar myObj = {1:[1,2,3],2:[4,5,6]};
– Qwerty
Aug 1 '14 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
Apr 14 '15 at 0:36
add a comment |
ECMASCRIPT 5:
Object.keys(myObj).map(function(x) { return myObj[x]; })
ECMASCRIPT 2015 or ES6:
Object.keys(myObj).map(x => myObj[x])
add a comment |
How about jQuery.makeArray(obj)
This is how I did it in my app.
2
This returns [Object] for the above example.
– Kris Erickson
Sep 30 '14 at 19:00
1
just a matter of adding [0] index and you saved my life :)
– Raheel Khan
Mar 24 '15 at 13:54
add a comment |
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];
});
add a comment |
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()
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']?
– Alex Werner
Sep 19 '16 at 12:37
add a comment |
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.
add a comment |
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;
};
add a comment |
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);
add a comment |
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...
add a comment |
ES8 way made easy:
The official documentation
const obj = { x: 'xxx', y: 1 };
let arr = Object.values(obj); // ['xxx', 1]
console.log(arr);add a comment |
18 Answers
18
active
oldest
votes
18 Answers
18
active
oldest
votes
active
oldest
votes
active
oldest
votes
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]]
7
@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
Feb 4 '14 at 15:57
20
D'oh! Ignore my comment. I hadn't noticed the jQuery tag on this question.
– crantok
Feb 4 '14 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.
– TD_Nijboer
Apr 9 '14 at 11:59
52
You can also do this without jQuery: Object.keys(myObject).map(function(val) { return [val] });
– Kris Erickson
Sep 30 '14 at 19:04
3
@TD_Nijboer Yes, usevalue.key = index; return [value];instead ofreturn [value];
– Simon Arnold
Nov 5 '14 at 18:38
|
show 16 more comments
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]]
7
@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
Feb 4 '14 at 15:57
20
D'oh! Ignore my comment. I hadn't noticed the jQuery tag on this question.
– crantok
Feb 4 '14 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.
– TD_Nijboer
Apr 9 '14 at 11:59
52
You can also do this without jQuery: Object.keys(myObject).map(function(val) { return [val] });
– Kris Erickson
Sep 30 '14 at 19:04
3
@TD_Nijboer Yes, usevalue.key = index; return [value];instead ofreturn [value];
– Simon Arnold
Nov 5 '14 at 18:38
|
show 16 more comments
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]]
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]]
edited Sep 20 '13 at 18:21
Nathan J. Brauer
8,11432535
8,11432535
answered Jul 28 '11 at 10:40
DogbertDogbert
152k28240265
152k28240265
7
@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
Feb 4 '14 at 15:57
20
D'oh! Ignore my comment. I hadn't noticed the jQuery tag on this question.
– crantok
Feb 4 '14 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.
– TD_Nijboer
Apr 9 '14 at 11:59
52
You can also do this without jQuery: Object.keys(myObject).map(function(val) { return [val] });
– Kris Erickson
Sep 30 '14 at 19:04
3
@TD_Nijboer Yes, usevalue.key = index; return [value];instead ofreturn [value];
– Simon Arnold
Nov 5 '14 at 18:38
|
show 16 more comments
7
@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
Feb 4 '14 at 15:57
20
D'oh! Ignore my comment. I hadn't noticed the jQuery tag on this question.
– crantok
Feb 4 '14 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.
– TD_Nijboer
Apr 9 '14 at 11:59
52
You can also do this without jQuery: Object.keys(myObject).map(function(val) { return [val] });
– Kris Erickson
Sep 30 '14 at 19:04
3
@TD_Nijboer Yes, usevalue.key = index; return [value];instead ofreturn [value];
– Simon Arnold
Nov 5 '14 at 18:38
7
7
@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
Feb 4 '14 at 15:57
@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
Feb 4 '14 at 15:57
20
20
D'oh! Ignore my comment. I hadn't noticed the jQuery tag on this question.
– crantok
Feb 4 '14 at 16:04
D'oh! Ignore my comment. I hadn't noticed the jQuery tag on this question.
– crantok
Feb 4 '14 at 16:04
8
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.
– TD_Nijboer
Apr 9 '14 at 11:59
is there a way to maintain the keys in the new array? every answer on the www i see lacks the conversion of keys.
– TD_Nijboer
Apr 9 '14 at 11:59
52
52
You can also do this without jQuery: Object.keys(myObject).map(function(val) { return [val] });
– Kris Erickson
Sep 30 '14 at 19:04
You can also do this without jQuery: Object.keys(myObject).map(function(val) { return [val] });
– Kris Erickson
Sep 30 '14 at 19:04
3
3
@TD_Nijboer Yes, use
value.key = index; return [value]; instead of return [value];– Simon Arnold
Nov 5 '14 at 18:38
@TD_Nijboer Yes, use
value.key = index; return [value]; instead of return [value];– Simon Arnold
Nov 5 '14 at 18:38
|
show 16 more comments
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)
3
Lodash docs say "iteration order is not guaranteed" though
– Karel Bílek
Mar 31 '15 at 18:51
9
@KarelBílek Is iteration order for a JS object ever guaranteed? 'An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function.'
– Meshaal
May 28 '15 at 1:35
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
Apr 6 '16 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
– Simon_Weaver
May 31 '16 at 2:41
For the first paragraph of code I get missing semi-colon. Not sure why.
– JohnnyBizzle
Aug 14 '16 at 15:52
|
show 5 more comments
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)
3
Lodash docs say "iteration order is not guaranteed" though
– Karel Bílek
Mar 31 '15 at 18:51
9
@KarelBílek Is iteration order for a JS object ever guaranteed? 'An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function.'
– Meshaal
May 28 '15 at 1:35
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
Apr 6 '16 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
– Simon_Weaver
May 31 '16 at 2:41
For the first paragraph of code I get missing semi-colon. Not sure why.
– JohnnyBizzle
Aug 14 '16 at 15:52
|
show 5 more comments
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)
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)
edited Sep 22 '16 at 18:00
Jean-François Beauchamp
3,08573265
3,08573265
answered Oct 2 '14 at 17:33
Joel RichardJoel Richard
13k53731
13k53731
3
Lodash docs say "iteration order is not guaranteed" though
– Karel Bílek
Mar 31 '15 at 18:51
9
@KarelBílek Is iteration order for a JS object ever guaranteed? 'An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function.'
– Meshaal
May 28 '15 at 1:35
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
Apr 6 '16 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
– Simon_Weaver
May 31 '16 at 2:41
For the first paragraph of code I get missing semi-colon. Not sure why.
– JohnnyBizzle
Aug 14 '16 at 15:52
|
show 5 more comments
3
Lodash docs say "iteration order is not guaranteed" though
– Karel Bílek
Mar 31 '15 at 18:51
9
@KarelBílek Is iteration order for a JS object ever guaranteed? 'An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function.'
– Meshaal
May 28 '15 at 1:35
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
Apr 6 '16 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
– Simon_Weaver
May 31 '16 at 2:41
For the first paragraph of code I get missing semi-colon. Not sure why.
– JohnnyBizzle
Aug 14 '16 at 15:52
3
3
Lodash docs say "iteration order is not guaranteed" though
– Karel Bílek
Mar 31 '15 at 18:51
Lodash docs say "iteration order is not guaranteed" though
– Karel Bílek
Mar 31 '15 at 18:51
9
9
@KarelBílek Is iteration order for a JS object ever guaranteed? 'An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function.'
– Meshaal
May 28 '15 at 1:35
@KarelBílek Is iteration order for a JS object ever guaranteed? 'An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function.'
– Meshaal
May 28 '15 at 1:35
3
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
Apr 6 '16 at 19:27
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
Apr 6 '16 at 19:27
1
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
– Simon_Weaver
May 31 '16 at 2:41
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
– Simon_Weaver
May 31 '16 at 2:41
For the first paragraph of code I get missing semi-colon. Not sure why.
– JohnnyBizzle
Aug 14 '16 at 15:52
For the first paragraph of code I get missing semi-colon. Not sure why.
– JohnnyBizzle
Aug 14 '16 at 15:52
|
show 5 more comments
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]);
}
}
}
1
You should have tested the code.$.mapwill flattenArray-Data.
– Marko Dumic
Jul 28 '11 at 10:35
you are right i didn't test it with an array and map flattens it! i modified the answer
– Nicola Peluchetti
Jul 28 '11 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.lengthshould return 2 (because 2 elements exists), but it returns 67 which is the number of all elements in all ["Array-Data"].
– The Bndr
Jul 28 '11 at 10:45
@The Bndr i posted another solution, but you can use map as suggested by dogbert
– Nicola Peluchetti
Jul 28 '11 at 10:46
I think you must explicitly specify the array index... likearr[+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.
– Salman A
Jul 28 '11 at 10:58
|
show 4 more comments
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]);
}
}
}
1
You should have tested the code.$.mapwill flattenArray-Data.
– Marko Dumic
Jul 28 '11 at 10:35
you are right i didn't test it with an array and map flattens it! i modified the answer
– Nicola Peluchetti
Jul 28 '11 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.lengthshould return 2 (because 2 elements exists), but it returns 67 which is the number of all elements in all ["Array-Data"].
– The Bndr
Jul 28 '11 at 10:45
@The Bndr i posted another solution, but you can use map as suggested by dogbert
– Nicola Peluchetti
Jul 28 '11 at 10:46
I think you must explicitly specify the array index... likearr[+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.
– Salman A
Jul 28 '11 at 10:58
|
show 4 more comments
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]);
}
}
}
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]);
}
}
}
edited Jul 28 '11 at 11:13
answered Jul 28 '11 at 10:29
Nicola PeluchettiNicola Peluchetti
62.2k24115165
62.2k24115165
1
You should have tested the code.$.mapwill flattenArray-Data.
– Marko Dumic
Jul 28 '11 at 10:35
you are right i didn't test it with an array and map flattens it! i modified the answer
– Nicola Peluchetti
Jul 28 '11 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.lengthshould return 2 (because 2 elements exists), but it returns 67 which is the number of all elements in all ["Array-Data"].
– The Bndr
Jul 28 '11 at 10:45
@The Bndr i posted another solution, but you can use map as suggested by dogbert
– Nicola Peluchetti
Jul 28 '11 at 10:46
I think you must explicitly specify the array index... likearr[+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.
– Salman A
Jul 28 '11 at 10:58
|
show 4 more comments
1
You should have tested the code.$.mapwill flattenArray-Data.
– Marko Dumic
Jul 28 '11 at 10:35
you are right i didn't test it with an array and map flattens it! i modified the answer
– Nicola Peluchetti
Jul 28 '11 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.lengthshould return 2 (because 2 elements exists), but it returns 67 which is the number of all elements in all ["Array-Data"].
– The Bndr
Jul 28 '11 at 10:45
@The Bndr i posted another solution, but you can use map as suggested by dogbert
– Nicola Peluchetti
Jul 28 '11 at 10:46
I think you must explicitly specify the array index... likearr[+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.
– Salman A
Jul 28 '11 at 10:58
1
1
You should have tested the code.
$.map will flatten Array-Data.– Marko Dumic
Jul 28 '11 at 10:35
You should have tested the code.
$.map will flatten Array-Data.– Marko Dumic
Jul 28 '11 at 10:35
you are right i didn't test it with an array and map flattens it! i modified the answer
– Nicola Peluchetti
Jul 28 '11 at 10:42
you are right i didn't test it with an array and map flattens it! i modified the answer
– Nicola Peluchetti
Jul 28 '11 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
Jul 28 '11 at 10:45
@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
Jul 28 '11 at 10:45
@The Bndr i posted another solution, but you can use map as suggested by dogbert
– Nicola Peluchetti
Jul 28 '11 at 10:46
@The Bndr i posted another solution, but you can use map as suggested by dogbert
– Nicola Peluchetti
Jul 28 '11 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.– Salman A
Jul 28 '11 at 10:58
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.– Salman A
Jul 28 '11 at 10:58
|
show 4 more comments
Simply do
Object.values(obj);
That's all!
11
Object.values is an ES2017 method that is not supported in Safari, IE, Node 6.
– Phil Ricketts
Jun 5 '17 at 15:48
add a comment |
Simply do
Object.values(obj);
That's all!
11
Object.values is an ES2017 method that is not supported in Safari, IE, Node 6.
– Phil Ricketts
Jun 5 '17 at 15:48
add a comment |
Simply do
Object.values(obj);
That's all!
Simply do
Object.values(obj);
That's all!
answered May 14 '17 at 21:58
PilaPila
1,7061020
1,7061020
11
Object.values is an ES2017 method that is not supported in Safari, IE, Node 6.
– Phil Ricketts
Jun 5 '17 at 15:48
add a comment |
11
Object.values is an ES2017 method that is not supported in Safari, IE, Node 6.
– Phil Ricketts
Jun 5 '17 at 15:48
11
11
Object.values is an ES2017 method that is not supported in Safari, IE, Node 6.
– Phil Ricketts
Jun 5 '17 at 15:48
Object.values is an ES2017 method that is not supported in Safari, IE, Node 6.
– Phil Ricketts
Jun 5 '17 at 15:48
add a comment |
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']]
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.
– user2000095-tim
Nov 8 '13 at 11:58
myObj.length = Object.keys(myObj).length
– baldrs
Dec 22 '16 at 10:18
add a comment |
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']]
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.
– user2000095-tim
Nov 8 '13 at 11:58
myObj.length = Object.keys(myObj).length
– baldrs
Dec 22 '16 at 10:18
add a comment |
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']]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']]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']]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']]edited Nov 15 '16 at 6:51
Rajesh
16.2k52253
16.2k52253
answered Jul 28 '11 at 10:54
bjorndbjornd
17.6k44366
17.6k44366
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.
– user2000095-tim
Nov 8 '13 at 11:58
myObj.length = Object.keys(myObj).length
– baldrs
Dec 22 '16 at 10:18
add a comment |
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.
– user2000095-tim
Nov 8 '13 at 11:58
myObj.length = Object.keys(myObj).length
– baldrs
Dec 22 '16 at 10:18
1
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.
– user2000095-tim
Nov 8 '13 at 11:58
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.
– user2000095-tim
Nov 8 '13 at 11:58
myObj.length = Object.keys(myObj).length– baldrs
Dec 22 '16 at 10:18
myObj.length = Object.keys(myObj).length– baldrs
Dec 22 '16 at 10:18
add a comment |
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
For the current ES5 (although I do enjoy ES6): Object.keys(yourObject).map(function(key){ return yourObject[key] });
– Macmee
Feb 18 '15 at 2:51
add a comment |
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
For the current ES5 (although I do enjoy ES6): Object.keys(yourObject).map(function(key){ return yourObject[key] });
– Macmee
Feb 18 '15 at 2:51
add a comment |
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]);
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]);
edited Oct 12 '15 at 17:13
radu
185
185
answered Dec 2 '14 at 17:26
MaxdowMaxdow
8621019
8621019
1
For the current ES5 (although I do enjoy ES6): Object.keys(yourObject).map(function(key){ return yourObject[key] });
– Macmee
Feb 18 '15 at 2:51
add a comment |
1
For the current ES5 (although I do enjoy ES6): Object.keys(yourObject).map(function(key){ return yourObject[key] });
– Macmee
Feb 18 '15 at 2:51
1
1
For the current ES5 (although I do enjoy ES6): Object.keys(yourObject).map(function(key){ return yourObject[key] });
– Macmee
Feb 18 '15 at 2:51
For the current ES5 (although I do enjoy ES6): Object.keys(yourObject).map(function(key){ return yourObject[key] });
– Macmee
Feb 18 '15 at 2:51
add a comment |
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).
if i do something likevar state = { ingredient: { salad: 1, bacon: 1, } }and thenvar HariOm = Object.values(state);followed byconsole.log(typeof HariOM)it displays the type as an object. Shouldn't it display it as an array?
– NoobieSatan
May 27 '18 at 21:07
That's completely normal, check the reference here : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - You can useArray.isArray(HariOM)
– Stopi
Aug 7 '18 at 13:59
add a comment |
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).
if i do something likevar state = { ingredient: { salad: 1, bacon: 1, } }and thenvar HariOm = Object.values(state);followed byconsole.log(typeof HariOM)it displays the type as an object. Shouldn't it display it as an array?
– NoobieSatan
May 27 '18 at 21:07
That's completely normal, check the reference here : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - You can useArray.isArray(HariOM)
– Stopi
Aug 7 '18 at 13:59
add a comment |
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).
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).
answered Feb 6 '18 at 3:12
StopiStopi
36628
36628
if i do something likevar state = { ingredient: { salad: 1, bacon: 1, } }and thenvar HariOm = Object.values(state);followed byconsole.log(typeof HariOM)it displays the type as an object. Shouldn't it display it as an array?
– NoobieSatan
May 27 '18 at 21:07
That's completely normal, check the reference here : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - You can useArray.isArray(HariOM)
– Stopi
Aug 7 '18 at 13:59
add a comment |
if i do something likevar state = { ingredient: { salad: 1, bacon: 1, } }and thenvar HariOm = Object.values(state);followed byconsole.log(typeof HariOM)it displays the type as an object. Shouldn't it display it as an array?
– NoobieSatan
May 27 '18 at 21:07
That's completely normal, check the reference here : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - You can useArray.isArray(HariOM)
– Stopi
Aug 7 '18 at 13:59
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?– NoobieSatan
May 27 '18 at 21:07
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?– NoobieSatan
May 27 '18 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
Aug 7 '18 at 13:59
That's completely normal, check the reference here : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - You can use
Array.isArray(HariOM)– Stopi
Aug 7 '18 at 13:59
add a comment |
x = ;
for( var i in myObj ) {
x[i] = myObj[i];
}
10
You should use push, otherwise you might end up creating an object
– Nicola Peluchetti
Jul 28 '11 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
Feb 19 '16 at 16:32
add a comment |
x = ;
for( var i in myObj ) {
x[i] = myObj[i];
}
10
You should use push, otherwise you might end up creating an object
– Nicola Peluchetti
Jul 28 '11 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
Feb 19 '16 at 16:32
add a comment |
x = ;
for( var i in myObj ) {
x[i] = myObj[i];
}
x = ;
for( var i in myObj ) {
x[i] = myObj[i];
}
answered Jul 28 '11 at 10:34
nobodynobody
9,15941936
9,15941936
10
You should use push, otherwise you might end up creating an object
– Nicola Peluchetti
Jul 28 '11 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
Feb 19 '16 at 16:32
add a comment |
10
You should use push, otherwise you might end up creating an object
– Nicola Peluchetti
Jul 28 '11 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
Feb 19 '16 at 16:32
10
10
You should use push, otherwise you might end up creating an object
– Nicola Peluchetti
Jul 28 '11 at 10:44
You should use push, otherwise you might end up creating an object
– Nicola Peluchetti
Jul 28 '11 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
Feb 19 '16 at 16:32
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
Feb 19 '16 at 16:32
add a comment |
The best method would be using a javascript -only function:
var myArr = Array.prototype.slice.call(myObj, 0);
4
This doesn't seem to work for me..:-/
– Qwerty
Jul 3 '14 at 10:37
@Qwerty which browser?
– test30
Jul 16 '14 at 8:47
Chrome. Tested withvar myObj = {1:[1,2,3],2:[4,5,6]};
– Qwerty
Aug 1 '14 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
Apr 14 '15 at 0:36
add a comment |
The best method would be using a javascript -only function:
var myArr = Array.prototype.slice.call(myObj, 0);
4
This doesn't seem to work for me..:-/
– Qwerty
Jul 3 '14 at 10:37
@Qwerty which browser?
– test30
Jul 16 '14 at 8:47
Chrome. Tested withvar myObj = {1:[1,2,3],2:[4,5,6]};
– Qwerty
Aug 1 '14 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
Apr 14 '15 at 0:36
add a comment |
The best method would be using a javascript -only function:
var myArr = Array.prototype.slice.call(myObj, 0);
The best method would be using a javascript -only function:
var myArr = Array.prototype.slice.call(myObj, 0);
answered May 26 '14 at 15:05
friederfrieder
1,1091131
1,1091131
4
This doesn't seem to work for me..:-/
– Qwerty
Jul 3 '14 at 10:37
@Qwerty which browser?
– test30
Jul 16 '14 at 8:47
Chrome. Tested withvar myObj = {1:[1,2,3],2:[4,5,6]};
– Qwerty
Aug 1 '14 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
Apr 14 '15 at 0:36
add a comment |
4
This doesn't seem to work for me..:-/
– Qwerty
Jul 3 '14 at 10:37
@Qwerty which browser?
– test30
Jul 16 '14 at 8:47
Chrome. Tested withvar myObj = {1:[1,2,3],2:[4,5,6]};
– Qwerty
Aug 1 '14 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
Apr 14 '15 at 0:36
4
4
This doesn't seem to work for me..
:-/– Qwerty
Jul 3 '14 at 10:37
This doesn't seem to work for me..
:-/– Qwerty
Jul 3 '14 at 10:37
@Qwerty which browser?
– test30
Jul 16 '14 at 8:47
@Qwerty which browser?
– test30
Jul 16 '14 at 8:47
Chrome. Tested with
var myObj = {1:[1,2,3],2:[4,5,6]};– Qwerty
Aug 1 '14 at 13:17
Chrome. Tested with
var myObj = {1:[1,2,3],2:[4,5,6]};– Qwerty
Aug 1 '14 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
Apr 14 '15 at 0:36
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
Apr 14 '15 at 0:36
add a comment |
ECMASCRIPT 5:
Object.keys(myObj).map(function(x) { return myObj[x]; })
ECMASCRIPT 2015 or ES6:
Object.keys(myObj).map(x => myObj[x])
add a comment |
ECMASCRIPT 5:
Object.keys(myObj).map(function(x) { return myObj[x]; })
ECMASCRIPT 2015 or ES6:
Object.keys(myObj).map(x => myObj[x])
add a comment |
ECMASCRIPT 5:
Object.keys(myObj).map(function(x) { return myObj[x]; })
ECMASCRIPT 2015 or ES6:
Object.keys(myObj).map(x => myObj[x])
ECMASCRIPT 5:
Object.keys(myObj).map(function(x) { return myObj[x]; })
ECMASCRIPT 2015 or ES6:
Object.keys(myObj).map(x => myObj[x])
answered May 12 '16 at 3:46
Aditya SinghAditya Singh
8,68792750
8,68792750
add a comment |
add a comment |
How about jQuery.makeArray(obj)
This is how I did it in my app.
2
This returns [Object] for the above example.
– Kris Erickson
Sep 30 '14 at 19:00
1
just a matter of adding [0] index and you saved my life :)
– Raheel Khan
Mar 24 '15 at 13:54
add a comment |
How about jQuery.makeArray(obj)
This is how I did it in my app.
2
This returns [Object] for the above example.
– Kris Erickson
Sep 30 '14 at 19:00
1
just a matter of adding [0] index and you saved my life :)
– Raheel Khan
Mar 24 '15 at 13:54
add a comment |
How about jQuery.makeArray(obj)
This is how I did it in my app.
How about jQuery.makeArray(obj)
This is how I did it in my app.
answered Jan 31 '14 at 21:24
Sankalp SinghaSankalp Singha
3,07433252
3,07433252
2
This returns [Object] for the above example.
– Kris Erickson
Sep 30 '14 at 19:00
1
just a matter of adding [0] index and you saved my life :)
– Raheel Khan
Mar 24 '15 at 13:54
add a comment |
2
This returns [Object] for the above example.
– Kris Erickson
Sep 30 '14 at 19:00
1
just a matter of adding [0] index and you saved my life :)
– Raheel Khan
Mar 24 '15 at 13:54
2
2
This returns [Object] for the above example.
– Kris Erickson
Sep 30 '14 at 19:00
This returns [Object] for the above example.
– Kris Erickson
Sep 30 '14 at 19:00
1
1
just a matter of adding [0] index and you saved my life :)
– Raheel Khan
Mar 24 '15 at 13:54
just a matter of adding [0] index and you saved my life :)
– Raheel Khan
Mar 24 '15 at 13:54
add a comment |
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];
});
add a comment |
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];
});
add a comment |
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];
});
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];
});
answered Sep 17 '17 at 16:08
Ivan FretesIvan Fretes
31836
31836
add a comment |
add a comment |
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()
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']?
– Alex Werner
Sep 19 '16 at 12:37
add a comment |
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()
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']?
– Alex Werner
Sep 19 '16 at 12:37
add a comment |
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()
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()
edited May 23 '17 at 11:33
Community♦
11
11
answered Jan 30 '14 at 7:28
Tushar GuptaTushar Gupta
42.3k188088
42.3k188088
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']?
– Alex Werner
Sep 19 '16 at 12:37
add a 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']?
– Alex Werner
Sep 19 '16 at 12:37
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']?
– Alex Werner
Sep 19 '16 at 12:37
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']?
– Alex Werner
Sep 19 '16 at 12:37
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited Apr 20 '17 at 14:50
answered Mar 10 '17 at 9:56
SupersharpSupersharp
13.5k22870
13.5k22870
add a comment |
add a comment |
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;
};
add a comment |
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;
};
add a comment |
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;
};
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;
};
answered May 16 '14 at 2:48
mailmindlinmailmindlin
4011621
4011621
add a comment |
add a comment |
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);
add a comment |
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);
add a comment |
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);
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);
edited Oct 14 '16 at 11:54
answered Oct 14 '16 at 10:44
KostasKostas
83112
83112
add a comment |
add a comment |
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...
add a comment |
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...
add a comment |
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...
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...
answered Jun 8 '17 at 9:49
AlirezaAlireza
47.7k12169121
47.7k12169121
add a comment |
add a comment |
ES8 way made easy:
The official documentation
const obj = { x: 'xxx', y: 1 };
let arr = Object.values(obj); // ['xxx', 1]
console.log(arr);add a comment |
ES8 way made easy:
The official documentation
const obj = { x: 'xxx', y: 1 };
let arr = Object.values(obj); // ['xxx', 1]
console.log(arr);add a comment |
ES8 way made easy:
The official documentation
const obj = { x: 'xxx', y: 1 };
let arr = Object.values(obj); // ['xxx', 1]
console.log(arr);ES8 way made easy:
The official documentation
const obj = { x: 'xxx', y: 1 };
let arr = Object.values(obj); // ['xxx', 1]
console.log(arr); const obj = { x: 'xxx', y: 1 };
let arr = Object.values(obj); // ['xxx', 1]
console.log(arr); const obj = { x: 'xxx', y: 1 };
let arr = Object.values(obj); // ['xxx', 1]
console.log(arr);answered Nov 14 '18 at 6:04
Black MambaBlack Mamba
2,75512139
2,75512139
add a comment |
add a comment |
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
Sep 12 '14 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]tomyObj= {0:[Array-Data]was not part of your edit (as I remember right)– The Bndr
Sep 17 '14 at 12:40
3
Use the jQuery $.makeArray(obj) command for that api.jquery.com/jQuery.makeArray
– DevlshOne
Mar 12 '15 at 16:38
@DevlshOne the documentation u provided says: "Turn a jQuery object into an array" i dont think this fits on OP question
– AXL
Nov 7 '18 at 9:05