我有一个像这样的对象数组
[
{"id": "1", "name": "test"},
{"id": "2", "name": "test2"},
{"id": "3", "name": "test3"}
]
我想将其转换为对象列表
{
"1": {"name": "test"},
"2": {"name": "test2"},
"3": {"name": "test3"},
}
最佳答案
您可以使用reduce :
var obj = arr.reduce(function(m,o){ m[o.id]={name:o.name}; return m }, {});
旁注:请务必阅读并尝试理解 T.J. 关于 JSON 的评论
关于javascript - 从数组创建对象到 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23362405/