Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 795
The Bndr Avatar asked Jul 28 '11 10:07

The Bndr


People also ask

How do I convert a JavaScript object array to a string array of the object attribute I want?

Stringify a JavaScript ArrayUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(arr); The result will be a string following the JSON notation.

How do I create an array in jQuery?

Syntax And Declaration:var arr1=[]; var arr2=[1,2,3]; var arr2=["India","usa","uk"]; Type of Array: The type of an array is “object“. Iteration Approach: We use the length property of the array to iterate in the array.

Can you push objects into an array JavaScript?

The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array.


2 Answers

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) 
like image 84
Joel Avatar answered Oct 15 '22 12:10

Joel


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]] 
like image 34
Dogbert Avatar answered Oct 15 '22 11:10

Dogbert