javascript 物件轉陣列


使用ajax時陣列資料傳送到前端時會呈現物件的狀態,這邊記錄一下將他轉換成array來使用的方式。

方法

下方紀錄兩種寫法都可以轉換

//物件資料
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}
//方法1
var result = Object.keys(obj).map((key) => [key, obj[key]]);
//方法2
var result = Object.entries(obj);

參考資料

https://stackoverflow.com/questions/38824349/how-to-convert-an-object-to-an-array-of-key-value-pairs-in-javascript

Tags : javascript