Convert flat array [k1,v1,k2,v2] to object {k1:v1,

2019-01-19 17:54发布

问题:

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 corresponding values (analgous to ruby's Hash[*array])?

For example, if I have this:

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

Then I want this:

{ 'a': 'b', 'c': 'd', 'e': 'f' }

The best I've come up with so far seems more verbose than it has to be:

var arr = [ 'a', 'b', 'c', 'd', 'e', 'f' ];
var obj = {};
for (var i = 0, len = arr.length; i < len; i += 2) {
    obj[arr[i]] = arr[i + 1];
}
// obj => { 'a': 'b', 'c': 'd', 'e': 'f' }

Is there a better, less verbose, or more elegant way to do this? (Or I have just been programming in ruby too much lately?)

I'm looking for an answer in vanilla javascript, but would also be interested if there is a better way to do this if using undercore.js or jQuery. Performance is not really a concern.

回答1:

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().



回答2:

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;

}, { } );


回答3:

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' }