[英]Lodash convert array to object
convert array to object the output should be same as key and value. 将数组转换为对象,输出应与键和值相同。
sample array:(my input structure) 示例数组:(我的输入结构)
var a = [1,2,3,4,5];
I need this structure of output: 我需要这种输出结构:
{
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5
}
你不需要一个库,只需一个标准的reduce :
let obj = [1,2,3,4,5].reduce((o,k)=>(o[k]=k,o), {})
You could map objects with same key and value, and assign all to an object. 您可以映射具有相同键和值的对象,并将所有对象分配给对象。
var array = [1, 2, 3, 4, 5], result = Object.assign({}, ...array.map(k => ({ [k]: k }))); console.log(result);
I use reduce here 我在这里使用reduce
const listToObject = list => list.reduce((obj, key) => { return { ...obj, [key]:key } }, {}) console.log(listToObject([1,2,3,4,5]))
You can use Object.fromEntries()
with Array.map()
: 您可以将
Object.fromEntries()
与Array.map()
:
var a = [1,2,3,4,5]; console.log( Object.fromEntries(a.map(v => [v, v])) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.