将分隔的字符串拆分为对象

时间:2015-09-27 13:41:14

标签: underscore.js lodash

我发现自己经常使用以下模式

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

你如何使用下划线使这更简洁和优雅?

2 个答案:

答案 0 :(得分:6)

使用下划线:

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

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

以上代码解释:

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

详细了解underscore's _.object here

使用Lodash:

Lodash等效方法是_.zipObject

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

答案 1 :(得分:1)

要将字符串解析为对象,可以使用JS Array.prototype.reduce或下划线_.reduce()

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

用法:

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

但是,如果您经常使用相同的分隔符,或者您必须解析具有相同属性的大量字符串,则下划线(或loadsh's)_.partial()非常方便:

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 - 检查左下方的面板,在控制台中查看结果。