Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a delimited string into an object

I find myself using often the following pattern

var line = "12|John Doe"
var pieces = line.split("|")
var user = {
   id : pieces[0],
   name : pieces[1]
} 
console.log(user)

How would you use underscore to make this more concise and elegant ?

like image 203
feralgeometry Avatar asked Sep 27 '15 13:09

feralgeometry


1 Answers

Using Underscore:

var user = _.object(['id', 'name'], line.split('|'));

console.log(user); // Object {id: "12", name: "John Doe"}

Above code explained:

var keys = ['id', 'name'];         // plain array of user field names
var values = line.split('|');      // splits line string to array of values
var user = _.object(keys, values); // joins both arrays as an object

Read more about underscore's _.object here.

Using Lodash:

Lodash equivalent method is _.zipObject.

var user = _.zipObject(['id', 'name'], line.split('|'));
like image 126
Ezequias Dinella Avatar answered Jan 01 '23 00:01

Ezequias Dinella