Skip to content Skip to sidebar Skip to footer

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)

Solution 1:

  • split the string at \n
  • loop through each line using map
  • Use match with the regex /(.*), (.*) \(.*\)\s+(.*)/ to get first name, last name into capturing groups (demo)
  • create an object from the array using 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)

Solution 2:

You can use regex to extract the data, use RegExp#exec method to extract data using a regular expression.

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 stringlet reg = /([\w ]+)\b\s?,\s?([\w ]+)\b\s*\([^)]+\)\s*([\w\d]+)/g;

// variable for storing matchlet m;

// object for the resultlet res = {};

// iterate over the matcheswhile (m = reg.exec(str)) {
// define object property based on the match
  res[`${m[2]}${m[1]}`] = m[3];
}

console.log(res);

Regex explanation here.

Post a Comment for "Convert A Multi-line String Into A Javascript Object"