Javascript- convert object to array


Question


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.


Answer 1:


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.




Answer 2:


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



来源:https://stackoverflow.com/questions/27521930/javascript-convert-object-to-array


码神部落- 版权声明 1、本主题所有言论和图片纯属会员个人意见,与码神部落立场无关。
2、本站所有主题由该帖子作者发表,该帖子作者撒浪嘿呦码神部落享有帖子相关版权。
3、码神部落管理员和版主有权不事先通知发贴者而删除本文。
4、其他单位或个人使用、转载或引用本文时必须同时征得该帖子作者撒浪嘿呦码神部落的同意。
5、帖子作者须承担一切因本文发表而直接或间接导致的民事或刑事法律责任。
6、本帖部分内容转载自其它媒体,但并不代表本站赞同其观点和对其真实性负责。
7、如本帖侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意。

最新回复 (0)
    • 码神部落
      2
        立即登录 立即注册 GitHub登录
返回
发新帖
作者最近主题: