我想像这样转换一个对象:
{"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
输入一个键值对数组,如下所示:
[[1,5],[2,7],[3,0],[4,0]...].
如何将对象转换为JavaScript中的键值对数组?
我想像这样转换一个对象:
{"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
输入一个键值对数组,如下所示:
[[1,5],[2,7],[3,0],[4,0]...].
如何将对象转换为JavaScript中的键值对数组?
当前回答
使用对象。以键值格式获取Object的每个元素,然后像这样映射它们:
var obj = {“1”:5,“2”:7,“3”:0,“4”:0,“5”:0,“6”:0,“7”:0,“8”:0,“9”:0,“10”:0,“11”:0,“12”:0} var res = Object.entries(obj).map(([k, v]) => ([Number(k), v])); console.log(res);
但是,如果你确定键是按递进顺序排列的,你可以使用Object。values和Array#map来做这样的事情:
var obj ={“2”,“1”:5:7,“3”:0,“4”:0,“5”:0,“6”:0,“7”:0,“8”:0,“9”:0,“10”:0,“11”:0,“12”:0}; // idx是索引,你可以使用任何逻辑来增加它(从0开始) let result = Object.values(obj)。Map ((e, idx) => ([++idx, e])); console.log(结果);
其他回答
我们可以将数字改为字符串类型的键如下所示:
var obj = {“1”:5,“2”:7,“3”:0,“4”:0,“5”:0,“6”:0,“7”:0,“8”:0,“9”:0,“10”:0,“11”:0,“12”:0} var result = Object.keys(obj).map(function(key) { 返回 [字符串(键), 对象[键]]; }); 控制台.log(结果);
下面是es6使用扩展操作符和Object.entries的“新”方法。
const data = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};
const dataSpread = [...Object.entries(data)];
// data spread value is now:
[
[ '1', 5 ], [ '2', 7 ],
[ '3', 0 ], [ '4', 0 ],
[ '5', 0 ], [ '6', 0 ],
[ '7', 0 ], [ '8', 0 ],
[ '9', 0 ], [ '10', 0 ],
[ '11', 0 ], [ '12', 0 ]
]
使用对象。key和array# map方法。
Var obj = { “1”:5 “2”:7, “3”:0, “4”:0, “5”:0, “6”:0, “7”:0, “8”:0, “9”:0, “10”:0, “十一”:0, “12”:0 }; //获取所有对象属性名 var res = Object.keys(obj) //遍历它们并生成数组 . map(函数(k) { //生成数组元素 返回[+k, obj[k]]; }); console.log (res);
这是我的解决方案,我有同样的问题,似乎这个解决方案为我工作。
yourObj = [].concat(yourObj);
使用for in
var obj = { "10":5, "2":7, "3":0, "4":0, "5":0, "6":0, "7":0,
"8":0, "9":0, "10":0, "11":0, "12":0 };
var objectToArray = function(obj) {
var _arr = [];
for (var key in obj) {
_arr.push([key, obj[key]]);
}
return _arr;
}
console.log(objectToArray(obj));