Ahsan Ahmad Raheel
Ahsan Ahmad Raheel

Reputation: 303

Make object from an array of key-value pairs using Lodash

I am using Lodash to create an object from an array but the result is not what I expected. Here is the code:

var _ = require('lodash');
var data = [ 
  [ 'creds', 'ZHRyYWhlZMMKDWhzYW5EaG1hZDE=' ],
  [ 'loggedIn', true ],
];
var result = _.zipObject(data);

Now the result is:

{creds,ZHRyYWhlZMMKDWhzYW5EaG1hZDE=: undefined, loggedIn,true: undefined}

but what I need is:

{'creds':'ZHRyYWhlZMMKDWhzYW5EaG1hZDE=', 'loggedIn':true}

Upvotes: 2

Views: 5664

Answers (4)

Hassan Imam
Hassan Imam

Reputation: 22534

You can use array#reduce to get object from your array.

var data = [ [ 'creds', 'ZHRyYWhlZMMKDWhzYW5EaG1hZDE=' ],[ 'loggedIn', true ] ];
var obj = data.reduce((o, [k,v]) => (o[k] = v, o), {});
console.log(obj);

Upvotes: 1

31piy
31piy

Reputation: 23859

You are close! The only difference is that _.zipObject expects two different parameters (one for keys, one for values), instead of an array of parameters.

But you should be able to do this by using .apply on _.zipObject method:

_.zipObject.apply(null, data);
// Object { creds: "loggedIn", "ZHRyYWhlZMMKDWhzYW5EaG1hZDE=": true }

Upvotes: 1

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

Using lodash's _.fromPairs:

var result = _.fromPairs(data);

Upvotes: 8

gurvinder372
gurvinder372

Reputation: 68393

You can also use reduce

result = data.reduce((a, b, i) => (a = i == 1 ? {
  [a[0]]: a[1]
} : a, a[b[0]] = b[1], a));

Demo

var data = [
  ['creds', 'ZHRyYWhlZMMKDWhzYW5EaG1hZDE='],
  ['loggedIn', true]
];

result = data.reduce((a, b, i) => (a = i == 1 ? {
  [a[0]]: a[1]
} : a, a[b[0]] = b[1], a));

console.log(result);

Upvotes: 1

Related Questions