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

时间:2019-03-22 05:36:49

标签: javascript regex

我的原始数据如下:

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

我想使用键和值将其转换为可循环对象,例如:

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

如何将其转换为javascript对象?我认为stringify可能是一个很好的起点。 FirstName具有不同的值。它们只是为了示范

2 个答案:

答案 0 :(得分:1)

  • split \n处的字符串
  • 使用map
  • 在每一行中循环
  • 使用match和正则表达式/(.*), (.*) \(.*\)\s+(.*)/将名字和姓氏分成捕获组( demo
  • 使用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)

答案 1 :(得分:0)

您可以使用正则表达式提取数据,使用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.