简体   繁体   English

将多行字符串转换为 javascript 对象

[英]Convert a multi-line string into a javascript object

I've my raw data that looks like this:我的原始数据如下所示:

Last Name, First Name (Details-Details)      #ID
Last Name, First Name (Details-Details)      #ID
Last Name, First Name (Details-Details)      #ID
Last Name, First Name (Details-Details)      #ID
Last Name, First Name (Details-Details)      #ID
Last Name, First Name (Details-Details)      #ID
x1000

I'd like to convert into a loopable object with keys and values something like:我想转换成一个带有键和值的可循环对象,例如:

var d = {
    "FirstName LastName": "#ID";
    "FirstName LastName": "#ID";
    "FirstName LastName": "#ID";
    "FirstName LastName": "#ID";
    "FirstName LastName": "#ID";
    "FirstName LastName": "#ID";
};

How can convert this to a javascript object?如何将其转换为 javascript 对象? I'm thinking stringify may be a good starting point.我认为stringify可能是一个很好的起点。 FirstName have different values. FirstName具有不同的值。 They are just for the purpose of demonstration它们仅用于演示目的

  • split the string at \\n\\nsplit字符串
  • loop through each line using map使用map遍历每一行
  • Use match with the regex /(.*), (.*) \\(.*\\)\\s+(.*)/ to get first name, last name into capturing groups ( demo )使用match正则表达式/(.*), (.*) \\(.*\\)\\s+(.*)/将名字,姓氏放入捕获组(演示
  • create an object from the array using reduce使用reduce从数组创建一个对象

 let str = `LastName1, FirstName1 (Details-Details) #ID1 LastName2, FirstName2 (Details-Details) #ID2 LastName3, FirstName3 (Details-Details) #ID3` let output = str.split("\\n") .map(a => a.match(/(.*), (.*) \\(.*\\)\\s+(.*)/)) .reduce((r, [, last, first, id]) => { r[`${first} ${last}`] = id return r; },{}) console.log(output)

You can use regex to extract the data, use RegExp#exec method to extract data using a regular expression.您可以使用正则表达式提取数据,使用RegExp#exec方法使用正则表达式提取数据。

 var str = `Last Name1, First Name1 (Details-Details) j1 Last Name2, First Name2 (Details-Details) 32 Last Name3, First Name3 (Details-Details) 3 Last Nam4e, First Name4 (Details-Details) 4 Last Name5, First Name5 (Details-Details) 5 Last Name6, First Name6 (Details-Details) 6` // pattern for matching the string let reg = /([\\w ]+)\\b\\s?,\\s?([\\w ]+)\\b\\s*\\([^)]+\\)\\s*([\\w\\d]+)/g; // variable for storing match let m; // object for the result let res = {}; // iterate over the matches while (m = reg.exec(str)) { // define object property based on the match res[`${m[2]} ${m[1]}`] = m[3]; } console.log(res);

Regex explanation here.正则表达式解释在这里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM