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) {
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"; var strToObjWithDelimiter = _.partial(str2Obj, '|'); console.log(strToObjWithDelimiter(['id', 'name'], str1)); console.log(strToObjWithDelimiter(['id', 'address', 'phone'], str3)); var userStr2Obj = _.partial(strToObjWithDelimiter, ['id', 'name']); console.log([str1, str2].map(userStr2Obj));
Fiddle - check the bottom left panel to see the results in the console.
source share