mreoer mreoer - 1 year ago 165
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 Source

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}, {});


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download