【问题标题】:How to convert an array to an object in Javascript without using loops?如何在不使用循环的情况下将数组转换为 Javascript 中的对象?
【发布时间】:2019-05-03 00:23:57
【问题描述】:

我要转换以下数组:

['a', 'b', 'c']

到以下对象:

{a: 'a', b: 'b', c: 'c'}

当然,不使用循环我该怎么做?

【问题讨论】:

  • 你必须使用某种循环。甚至内置数组方法也使用循环
  • @charlietfl 我正在寻找更短的,也许是传播运算符?
  • {...['a', 'b', 'c']} 结果为{0: "a", 1: "b", 2: "c"}。没有 map、reduce 或类似的循环就无法完成
  • 扩展运算符无论如何都在数组上循环
  • 选择你的循环...while、for、forEach、map、reduce、reduceRight 等...没有办法避免其中之一。一旦你选择了你想要使用的循环,没有什么复杂的

标签: javascript arrays object types


【解决方案1】:

您可以使用Array#reduce 来获得想要的结果。

const a = ['a', 'b', 'c'];
const o = a.reduce((s, a) => {
   s[a] = a;
   return s;
}, {});

console.log(o);

【讨论】:

    【解决方案2】:

    您可以使用Object.assign 映射对象并连接到单个对象。

    var array = ['a', 'b', 'c'],
        object = Object.assign(...array.map(v => ({ [v]: v })));
        
    console.log(object);

    【讨论】:

    • 不使用地图有什么办法吗?
    • 为什么不用地图?
    • map 没问题,但使用扩展运算符可能会更短?
    【解决方案3】:

    使用reduce

    var arr = ['a', 'b', 'c'];
    
    
    var obj = arr.reduce(function(obj, value) {
         obj[value] = value;
         return obj
    }, {});
    console.log(obj)

    【讨论】:

      【解决方案4】:

      object.assign() 可能会解决您的问题。

      这是一个例子。

      var array = ['a', 'b', 'c']; 
      
      Object.assign( {}, array);
      
      // {0: "a", 1: "b", 2: "c"}
      

      新对象将与数组具有相同的索引。

      如果您希望数组的值与键相同。

      function arrayToObject( array) 
      {  
          var object = array.reduce( (obj, value) => {
              obj[value] = value;
              return obj
          }, {});
          return object;
      }
      arrayToObject( ['a', 'b', 'c'])
      

      【讨论】:

      • @trincot 感谢提及。我其实以为他们是一样的,
      【解决方案5】:

      您需要使用Array.reduce() 方法。

      reduce() 方法对数组的每个成员执行(您提供的)reducer 函数,从而产生单个输出值。

      arr.reduce(callback[, initialValue])
      

      reduce() 回调方法接受accumulatorcurrentValue 参数。

      • 累加器:在方法的每次迭代中都会记住值,并最终成为最终的返回值。
      • currentValue:array中正在处理的当前元素。

      {} 作为reduce() 的最后一个参数提供,作为开始的初始值。随着Array 的每次迭代,我们添加到它最终创建最终的Object

      示例: (ES6)

      const letters = ['a', 'b', 'c'];
      
      const obj = letters.reduce((accumulator, currentValue) => {
        accumulator[currentValue] = currentValue;
        return accumulator;
      }, {});
      
      console.log(obj);

      示例: (ES5)

      var letters = ['a', 'b', 'c'];
      
      var obj = letters.reduce(function (accumulator, currentValue) {
        accumulator[currentValue] = currentValue;
        return accumulator;
      }, {});
      
      console.log(obj);

      参考: Array.prototype.reduce() mozilla 文档。

      【讨论】:

        【解决方案6】:

        这可能是最短的版本:

        console.log( ['a', 'b', 'c'].reduce((o, v) => (o[v] = v, o), {}) )

        【讨论】:

          【解决方案7】:

          另一种解决方案,您也可以将较新的Object.fromEntries 与地图一起使用。

          let arr = ['a', 'b', 'c'];
          
          let obj = Object.fromEntries(arr.map(m => [m,m]));
          
          console.log(obj);

          【讨论】:

            【解决方案8】:

            常量值 = ['a', 'b', 'c'] const objectValues = {...values} =>

            const values = ['a', 'b', 'c']
            
            const objectValues = {...values}
            
            console.log(objectValues)

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-01-07
              • 2022-10-05
              • 2017-10-24
              • 2014-05-02
              • 2019-02-16
              • 2016-03-24
              • 2020-08-23
              • 2023-03-29
              相关资源
              最近更新 更多