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 ?
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.
Lodash equivalent method is _.zipObject.
var user = _.zipObject(['id', 'name'], line.split('|'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With