Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break a string into an array of objects

Tags:

javascript

I want to break this string:

data=

1.

Title: The Definitive Guide
Copy: There’s no way around it, 
URL: http://www.schools
Date: 6/7/17

2.

Title: Using 
Copy: Today’s fast
URL: https://blog
Date: 6/16/17
3.

Title: 4 Ways 
Copy: Let’s state
URL: https://www.
Date: 6/20/17

into an array of length=3 in this case (one for each of the numbering above). Each array item should be an object with the properties: title, copy, url, date.

I've tried this:

for(let i=0; i<3; i++) {

    arr[i] =temp.split(i+2 + ".");
    temp=temp.slice(0, arr[i].length);


};

Perhaps there is a simpler string method even. Could not find something similar looking in past questions published in SO.

like image 709
ddy250 Avatar asked Mar 18 '26 14:03

ddy250


1 Answers

I would opt for simply reading this line-by-line. Your lines will either be a number and a dot, empty space, or data. That's easy enough to loop through without getting involved in complex regexes:

data=`

1.

Title: The Definitive Guide
Copy: There’s no way around it, 
URL: http://www.schools
Date: 6/7/17

2.

Title: Using 
Copy: Today’s fast
URL: https://blog
Date: 6/16/17
31.

Title: 4 Ways 
Copy: Let’s state
URL: https://www.
Date: 6/20/17
`
let current, final = []
data.split('\n').forEach(line => {
  if (/^\d+\./.test(line)) final.push(current = {}) // new block
  else if (/\S/.test(line)){                        // some data
    let split = line.indexOf(":")
    let key = line.slice(0, split)
    let val = line.slice(split +1)
    current[key] = val.trim()
  }
})
console.log(final)

This assumes the data is clean. If there's a possibility of extraneous non-data lines, then you'll need to d a bit more work, but I think the basic idea would still work.

like image 174
Mark Avatar answered Mar 20 '26 04:03

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!