Convert flat array [k1,v1,k2,v2] to object {k1:v1,k2:v2} in JavaScript?

前端 未结 3 484
旧时难觅i
旧时难觅i 2020-12-11 05:37

Is there a simple way in javascript to take a flat array and convert into an object with the even-indexed members of the array as properties and odd-indexed members as corre

相关标签:
3条回答
  • 2020-12-11 06:08
    var arr = [ 'a', 'b', 'c', 'd', 'e', 'f' ];
    var obj = arr.reduce( function( ret, value, i, values ) {
    
        if( i % 2 === 0 ) ret[ value ] = values[ i + 1 ];
        return ret;
    
    }, { } );
    
    0 讨论(0)
  • 2020-12-11 06:26

    Pretty sure this will work and is shorter:

    var arr = [ 'a', 'b', 'c', 'd', 'e', 'f' ];
    var obj = {};
    while (arr.length) {
        obj[arr.shift()] = arr.shift();
    }
    

    See shift().

    0 讨论(0)
  • 2020-12-11 06:29

    If you need it multiple times you can also add a method to the Array.prototype:

    Array.prototype.to_object = function () {
      var obj = {};
      for(var i = 0; i < this.length; i += 2) {
        obj[this[i]] = this[i + 1]; 
      }
      return obj
    };
    
    var a = [ 'a', 'b', 'c', 'd', 'e', 'f' ];
    
    a.to_object();    // => { 'a': 'b', 'c': 'd', 'e': 'f' }
    
    0 讨论(0)
提交回复
热议问题