[英]How to convert this type of arrays into a json object?
我有這個數組:
[ [ '560134275538747403', 39953 ],
[ '411510958020624384', 36164 ],
[ '468512396948930576', 31762 ],
[ '482286641982078977', 29434 ],
[ '249892869127536641', 6295 ] ]
我想將其隱藏成這樣的對象:
{
"560134275538747403":39953,
"411510958020624384":36164,
"468512396948930576":31762,
"482286641982078977":29434,
"249892869127536641":6295
}
無論如何要這樣做? 〜和thx
使用Object.fromEntries
:
const arr=[['560134275538747403',39953],['411510958020624384',36164],['468512396948930576',31762],['482286641982078977',29434],['249892869127536641',6295]]; const res = Object.fromEntries(arr); console.log(res);
或者,由於未得到廣泛支持,請reduce
:
const arr=[['560134275538747403',39953],['411510958020624384',36164],['468512396948930576',31762],['482286641982078977',29434],['249892869127536641',6295]]; const res = arr.reduce((a, [k, v]) => (a[k] = v, a), {}); console.log(res);
您可以使用ES2019功能Object.fromEntries(...)
,
const array=[ [ '560134275538747403', 39953 ], [ '411510958020624384', 36164 ], [ '468512396948930576', 31762 ], [ '482286641982078977', 29434 ], [ '249892869127536641', 6295 ] ]; const object=Object.fromEntries(array); console.log(object);
假設Node不支持它。 然后,您可以從npm https://www.npmjs.com/package/object.fromentries安裝它的墊片后才能使用它
這里是一個Runkit鏈接,顯示它的工作使用節點墊片, https://runkit.com/embed/lkupsniraw2c
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.