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.
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?
2
Answers
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.