简体   繁体   English

如何将这种类型的数组转换为json对象?

[英]How to convert this type of arrays into a json object?

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 〜和thx

Either use Object.fromEntries : 使用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 : 或者,由于未得到广泛支持,请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(...) , 您可以使用ES2019功能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. 假设Node不支持它。 Then you can use it after you install a shim of it from npm, https://www.npmjs.com/package/object.fromentries 然后,您可以从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 这里是一个Runkit链接,显示它的工作使用节点垫片, https://runkit.com/embed/lkupsniraw2c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM