mreoer mreoer - 2 months ago 23
Javascript Question

Convert key-value array to object using lodash

I have an array with key value sequence (first element is a key, second - value etc.)

var arr = ['a',1,'b',2,'c',3];


I need to convert this array to object using lodash. How can I do this?

result = {
a : 1,
b : 2,
c : 3
};

Answer

If it's every other value, you could just reduce that

var arr = ['a',1,'b',2,'c',3];

var obj = arr.reduce( (a,b,i) => {return i%2===0 ? (a[arr[i]] = arr[i+1],a) : a}, {});

console.log(obj)

Comments