[英]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.