Skip to content Skip to sidebar Skip to footer

Convert Flat Array [k1,v1,k2,v2] To Object {k1:v1,k2:v2} In Javascript?

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 correspondin

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

Solution 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;

}, { } );

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

Solution 4:

You could first chunk your array into groups of two:

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

so that is is in a valid format to be used by Object.fromEntries(), which will build your object for you:

constchunk = (arr, size) => arr.length ? [arr.slice(0, size), ...chunk(arr.slice(size), size)] : [];
const arr = ['a', 'b', 'c', 'd', 'e', 'f'];
const res = Object.fromEntries(chunk(arr, 2));
console.log(res); // {a: "b", c: "d", e: "f"}

With underscore.js and lodash, you don't need to implement the chunk() method yourself, and can instead use _.chunk(), a method built into both libraries. The full lodash equivalent of the above would be:

// lodash
> _.fromPairs(_.chunk(arr, 2)); 
> {a: "b", c: "d", e: "f"}

Using _.fromPairs provides better browser support, so if using lodash, it is preferred over Object.fromEntries()

Similarly, we can use _.object() if you're using underscore.js to build the object:

// underscore.js
> _.object(_.chunk(arr, 2));
> {a: "b", c: "d", e: "f"}

Post a Comment for "Convert Flat Array [k1,v1,k2,v2] To Object {k1:v1,k2:v2} In Javascript?"