EthanPrisonMike
EthanPrisonMike

Reputation: 47

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? I'm thinking stringify may be a good starting point. FirstName have different values. They are just for the purpose of demonstration

Upvotes: 1

Views: 2176

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115222

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 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.

Upvotes: 0

adiga
adiga

Reputation: 35222

  • 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)

Upvotes: 2

Related Questions