首页 > 解决方案 > 将数组中的每一项转换为对象

问题描述

我想知道如何将数组中的每个项目转换为指定的对象。您可以在下面看到我开始使用的数组的代码以及我想要达到的结果。我试图使用该map功能无济于事,并且不确定该array.map()功能是否是正确使用的功能,或者是否可以使用 lodash 中的某些东西。谢谢!

const x = ["a", "b", "c"];

// expected result
{
  "a": {"foo": "bar"},
  "b": {"foo": "bar"},
  "c": {"foo": "bar"},
}

标签: javascriptlodash

解决方案


您可以使用Array#reduce()

const x = ["a", "b", "c"];

const res = x.reduce((a,c)=> (a[c] = {foo:'bar'},a) , {})

console.log(res)


推荐阅读