我想知道如何将数组中的每个项目转换为指定的对象。您可以在下面看到我开始使用的数组的代码以及我试图实现的结果。我试图使用 map
函数无济于事,并且不确定 array.map()
函数是否是正确的函数,或者是否有我可以使用的 lodash 中的东西。谢谢!
const x = ["a", "b", "c"];
// expected result
{
"a": {"foo": "bar"},
"b": {"foo": "bar"},
"c": {"foo": "bar"},
}
最佳答案
您可以使用Array#reduce()
const x = ["a", "b", "c"];
const res = x.reduce((a,c)=> (a[c] = {foo:'bar'},a) , {})
console.log(res)
关于javascript - 将数组中的每个项目转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53785953/