代码之家  ›  专栏  ›  技术社区  ›  magicgregz

如何将javascript数组转换为对象?[关闭]

  •  -9
  • magicgregz  · 技术社区  · 7 年前

    最好的转换方法是什么

    ['a', 'b', 'c', 'd', 'e', 'f']
    

    进入:

    {
      "a": "b", 
      "c": "d",
      "e": "f"
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   barbsan Cibi    7 年前

    for

     Array.prototype.toObject  = function(){
     // var len = this.length -1; // omit 'e' property
      var len = this.length; // leave 'e' property
     
      var obj = {};
      
      for (var i = 0; i< len; i=i+2){
        obj[this[i]] = this[i+1];
      }
      
      return obj;
    }
    
    var arr1 = ['a', 'b', 'c', 'd', 'e']
    
    console.log(arr1.toObject())
        2
  •  -4
  •   magicgregz    7 年前

     Array.prototype.toObject  = function(){
       // var length = this.length - 1;
       return this.reduce(function(obj, val, index, array) {
          if(index %2 != 0) return obj;
          // if(index == length) return obj; // leave the 'e' property
          obj[val] = array[index+1];
          return obj;
       }, {})
     }
     
     
    var a = ['a', 'b', 'c','d', 'e', 'f'];
    console.log(a.toObject());