Split a delimited string into an object

I often use 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 underline to make it more concise and elegant?

+5
source share
2 answers

Using Underscore:

 var user = _.object(['id', 'name'], line.split('|')); console.log(user); // Object {id: "12", name: "John Doe"} 

Above code:

 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 _.object here .

Using Lodash:

Lodash Equivalence Method _. zipObject .

 var user = _.zipObject(['id', 'name'], line.split('|')); 
+6
source

To parse a string for an object, you can use JS Array.prototype.reduce or underline _ reduce () :.

 function str2Obj(delimiter, props, str) { return str.split(delimiter) .reduce(function (obj, value, index) { // you can use underscore reduce instead obj[props[index]] = value; return obj; }, {}); } 

Using:

 var str1 = "12|John Doe"; console.log(str2Obj('|', ['id', 'name'], str1)); 

However, if you often use the same separator or if you need to parse a large number of rows with the same properties, underline (or loadsh's) _. partial () is very convenient:

 var str2 = "13|John Smith"; var str3 = "id|address|phone"; /** create a partially applied function with the '|' delimiter **/ var strToObjWithDelimiter = _.partial(str2Obj, '|'); console.log(strToObjWithDelimiter(['id', 'name'], str1)); console.log(strToObjWithDelimiter(['id', 'address', 'phone'], str3)); /** create a partially applied function with the '|' delimiter, and a props list **/ var userStr2Obj = _.partial(strToObjWithDelimiter, ['id', 'name']); console.log([str1, str2].map(userStr2Obj)); // you can use _.map() as well 

Fiddle - check the bottom left panel to see the results in the console.

+1
source

Source: https://habr.com/ru/post/1232395/


All Articles