javascript - 将数组中的每一项转换为对象
问题描述
我想知道如何将数组中的每个项目转换为指定的对象。您可以在下面看到我开始使用的数组的代码以及我想要达到的结果。我试图使用该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)
推荐阅读
- python - 使用数据限制绘图(python)
- git - 气流如何使用 git sync 从 git 分支中的 dag 文件夹中获取 dag
- python - 在 Anaconda 中保存和打开 Python 脚本
- regex - 带有国家代码的电话号码的正则表达式
- python - OSMnx:检索多个城市的建筑多边形
- git - andriod studio 在哪里存储 git 密码?
- sql - 获得每个分区第一条记录的最佳方法:FIRST_VALUE vs ROW_NUMBER
- python - Dask - 是否可以在每个具有自定义功能的工作人员中使用所有线程?
- python - 使用 Python 从具有不同级别的嵌套列表和字典的 json 中提取数据
- pyspark - Pyspark:读取带有双引号和逗号的字段的csv文件