简体   繁体   中英

Javascript- convert object to array

I want to convert an Object to an array. The object is like this {1: 36, 3: 112, 6: 71} and i want it to convert it to this [[1,36],[3,112],[6,71]] . Actually the data is JSON then i want to use it as data for jqplot .

I have found answers as to converting object to array but mostly like this: from {1: 36, 3: 112, 6: 71} to [[36],[112],[71]] .

Any ideas regarding this one? Any help will be appreciated.

A simple solution :

var arr = [];
for (var k in obj) arr.push([+k, obj[k]]); 

+k is used to convert the key from a string (all object keys are strings) to a number.

You can use Object.keys and [].map

var arr = Object.keys(obj).map(function(k){ return [+k, obj[k]];  });

+k is same as Number(k) as Object.keys return an Array of String , but you want it in Number

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM