JavaScript数组到字典的映射无法正常工作?

时间:2018-10-14 11:18:53

标签: javascript arrays dictionary

我想将Java脚本数组映射到字典中

let myArray=['first','second','third'];

预期产量

result={first:1,second:1,third}

实际输出

result=[{element:1}, {element:1}, {element:1}]

代码:

let myArray=['first','second','third'];

let result=myArray.map(element=>{

    return {element:1}

})

4 个答案:

答案 0 :(得分:4)

您可以使用Object.assign并扩展语法。

let myArray=['first','second','third'];
let obj = Object.assign({}, ...myArray.map(key => ({[key]: 1})));
console.log(obj)

答案 1 :(得分:2)

let myArray=['first','second','third'];

let result = myArray.reduce((agg, ele) => {
   agg[ele] = 1;
   return agg;
}, {});

console.log(result);

答案 2 :(得分:2)

   let myArray=['first','second','third'];

   let result=myArray.reduce((obj, element)=>{ 

    return {...obj, [element]:1}
 }, {})

Reducer将增量地附加您的新密钥。数组键语法使用element的值作为新键

答案 3 :(得分:2)

为什么不只是常规的for循环?

  const result = {};
  for(const key of myArray)
    result[key] = 1;