这个数组转对象 有什么简单的写法吗?

let list = {}
let list2 = [1,2,4]
list2.map(res2=>{
          if(res2==1){
            list.item1 = true
          }
          if(res2==2){
            list.item2 = true
          }
          if(res2==3){
            list.item3 = true
          }
          if(res2==4){
            list.item4 = true
          }
})
阅读 2.6k
3 个回答
list2.forEach(n=>list[`item${n}`]=true)

题主的解法,嗯,就是把 if 链优化一下。不过 .map 可以改成 .forEach,毕竟不需要映射成另一个数组

解法一

观察 .item?list2 元素的关系,可以用 @SlimBear 的解法

const list = {};
list2.forEach(res => list[`item${res}`] = true);

解决二

直接生成对象,不需要提前准备,正解应该像 @zangeci 那样使用 .reduce(),不过这里可以偷懒

const list = Object.fromEntries(
    list2.map(n => [`item${n}`, true])
);

已参与了 SegmentFault 思否「问答」打卡,欢迎正在阅读的你也加入。
推荐问题
宣传栏