Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to turn string into objects with properties

I’m fetching a string that looks like this

Ebonie Rangel
7175 Yukon Street
(507) 833-3567
Geography
Keenan Ellwood
2 Elm Lane
(894) 831-6482
History
Kailan Smart
795 Harvard Street
(925) 856-5167
Biology
Kaydan Hirst
9 East Lakeview Ave.
(939) 812-6141
Programming
Isabelle Prentice
700 Rock Maple St.
(899) 875-8627
Math

and I’m trying to create an array of objects for each person from the string to have something like this

[
 {
  name: 'Ebonie Rangel',
  address: '7175 Yukon Street',
  phone: '(507) 833-3567',
  course: 'Geography'
 },
 {
  name: 'Keenan Ellwood,
  address: '2 Elm Lane',
  phone: '(894) 831-6482,
  course: 'History'
 },
 ...etc
];

What I’ve tried is to split the string and create an array, and then to map through it and create properties there with values, but the problem is the string I fetched is already broken down by something and I cannot figure it out by what I should split it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let button = document.getElementById('get-text-btn');
      let textArea = document.getElementById('my-text-area');
      
      button.addEventListener('click', function () {
        loader.style.display = 'inline-block';
        fetch('https://v-dresevic.github.io/Advanced-JavaScript-Programming/data/students.txt')
          .then(function (response) {
            if (response.status !== 200) {
              throw Error('Error while reading file.');
            }
            return response.text();
          })
          .then(function (text) {
            // textArea.innerHTML = text;
            const redovi = text.split('\n'); 

            const objekti = redovi.map((red) => {
              const [name, address, phone, course] = red.split('\n');

              return {
                name: name.trim(),
                address: address,
                phone: phone,
                course: course,
              };
            });
console.log(objekti)
          })
          .catch(function (err) {
            textArea.innerHTML = 'Fetch problem: ' + err.message;
          })
          .finally(function () {
            loader.style.display = 'none';
          });
      });
<button id="get-text-btn">Get Data</button>
    <div id="loader"></div>
    <textarea id="my-text-area" rows="30"></textarea>

What am I doing wrong?

>Solution :

You are using split ('\n') two times which does not make sense. After splitting the file into lines you have to count to know when the record is finished.

let button = document.getElementById('get-text-btn');
      let textArea = document.getElementById('my-text-area');
      
      button.addEventListener('click', function () {
        loader.style.display = 'inline-block';
        fetch('https://v-dresevic.github.io/Advanced-JavaScript-Programming/data/students.txt')
          .then(function (response) {
            if (response.status !== 200) {
              throw Error('Error while reading file.');
            }
            return response.text();
          })
          .then(function (text) {
            // textArea.innerHTML = text;
            const redovi = text.split('\n'); 
            
            let records = [];
            for (let i=0; i<redovi.length; i+=4)
            {
              records.push ({
                name: redovi[i].trim(),
                address: redovi[i+1].trim(),
                phone: redovi[i+2].trim(),
                course: redovi[i+3].trim(),
              });
            }
console.log(records)
          })
          .catch(function (err) {
            textArea.innerHTML = 'Fetch problem: ' + err.message;
          })
          .finally(function () {
            loader.style.display = 'none';
          });
      });
<button id="get-text-btn">Get Data</button>
    <div id="loader"></div>
    <textarea id="my-text-area" rows="30"></textarea>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading