方法一:Object.fromEntries()

Object.fromEntries() 用于js数组转对象

const arr = [  { name: "xiaoming", sex: "man" },  { name: "xiaohong", sex: "woman" },];
 
const obj = Object.fromEntries(arr.map(item => [item.name, item]));
 
console.log(obj); 
// {
//    xiaoming: { name: "xiaoming", sex: "man"  },
//    xiaohong: { name: "xiaohong", sex: "woman" }
// }

方法二:map循环方式

const arr = [  { name: "xiaoming", sex: "man" },  { name: "xiaohong", sex: "woman" },];
 
let obj={};
 
arr.map((ele, index) => {
    obj[ele.name] = ele
})
 
console.log(obj)
// {
//    xiaoming: { name: "xiaoming", sex: "man"  },
//    xiaohong: { name: "xiaohong", sex: "woman" }
// }

方法三:for in 循环方式

const arr = [  { name: "xiaoming", sex: "man" },  { name: "xiaohong", sex: "woman" },];
 
let obj={};
for (var item in arr){
  obj[arr[item].name] = arr[item];
};
 
console.log(obj)
// {
//    xiaoming: { name: "xiaoming", sex: "man"  },
//    xiaohong: { name: "xiaohong", sex: "woman" }
// }

总结

除了单独的方法 Object.fromEntries(),我们可以把数组转成对象,我们还可以用这种思路:

  1. 遍历数组,拿到数组中的每一项,有很多种遍历数组的方法,哪个熟悉用哪个,上述讲了两种(for in,map),还有很多..
  2. 然后创建一个空对象(let obj = {})
  3. 让数组中每一个对象的一个key作为新对象的,数组中的每一个对象作为key的value,(obj[ele.name] = ele)

扩展阅读