I have this array:
[ [ '560134275538747403', 39953 ],
[ '411510958020624384', 36164 ],
[ '468512396948930576', 31762 ],
[ '482286641982078977', 29434 ],
[ '249892869127536641', 6295 ] ]
And I want to covert it into an object like this:
{
"560134275538747403":39953,
"411510958020624384":36164,
"468512396948930576":31762,
"482286641982078977":29434,
"249892869127536641":6295
}
Anyway to do that? ~and thx
Either use Object.fromEntries
:
const arr=[['560134275538747403',39953],['411510958020624384',36164],['468512396948930576',31762],['482286641982078977',29434],['249892869127536641',6295]]; const res = Object.fromEntries(arr); console.log(res);
Or, as that's not widely supported, 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);
You can go ahead by using the ES2019 feature Object.fromEntries(...)
,
const array=[ [ '560134275538747403', 39953 ], [ '411510958020624384', 36164 ], [ '468512396948930576', 31762 ], [ '482286641982078977', 29434 ], [ '249892869127536641', 6295 ] ]; const object=Object.fromEntries(array); console.log(object);
Suppose if it isn't supported in Node. Then you can use it after you install a shim of it from npm, https://www.npmjs.com/package/object.fromentries
Here is a Runkit link that shows it working using the shim in Node, https://runkit.com/embed/lkupsniraw2c
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.