What is the process of transforming the contents of a file into strings?

I need to transform the contents of a txt file into a specific format:

1||fun||ball
2||job||hammer
3||run||feet

The desired output format is:

<dt>1</dt><dd>fun <img src="ball.png"></dd>
<dt>2</dt><dd>job <img src="hamm.png"></dd>
<dt>3</dt><dd>run <img src="feet.png"></dd>

I attempted the following code:

const openrooms = `1||fun||ball
     2||job||hamm
     3||run||feet`;

const roomlist = openrooms.split('\n');

for (var rooms in roomlist) {
  room = roomlist[rooms].split('||');
  for (var {roomid, name, icon} in room) {
    result = `<dt>${room[roomid]}</dt><dd>${room[name]} <img src="${room[icon]}"></dd>`;
  }
}
document.getElementById("destination").innerHTML = result;
<div id="destination"></div>

However, I only receive "undefined" as the result. Can someone please help me identify the issue? Feel free to test it using the fiddle link below:

https://jsfiddle.net/db6hy8a0/

Answer №1

Give it a shot:

const roomData = `1||apple||red
     2||cat||blue
     3||dog||green`;

const roomsList = roomData.split('\n');

const output = roomsList.map(item => {
  var splitItem = item.split('||')
  return `<dt>${splitItem[0]}</dt><dd>${splitItem[1]} <img src="${splitItem[2]}.png"></dd>`
}).join('')

document.getElementById("destination").innerHTML = output;
<div id="destination"></div>

Answer №2

The secondary loop makes an attempt to break down the strings from the second division.

Consider trying something along these lines:

const availableSpaces = `1||happy||sun
2||work||nail
3||walk||toes`
 
const spaces = availableSpaces.split('\n')

output = ""
spaces.forEach(place => {
  const [number, activity, tool] = place.split('||')
  output += `${number} space: ${activity} - ${tool}\n`
})

console.log(output)

(But why not simply save them in an object initially?)

Answer №3

let roomData = `1||happy||sun
 2||sad||moon
 3||sleepy||stars`;


const dataDisplay = roomData.split("\n").map((line)=> {
const elements = line.split("||");
return `<dt>${elements[0]}</dt><dd>${elements[1]} <img src="${elements[2]}.png"></dd>`
})


document.getElementById("dest").innerHTML = dataDisplay;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to activate Toast notification before the window's onbeforeunload event?

Here's a snippet of JavaScript that I have been working on. It currently pops up an alert when someone tries to leave a form without completing it. However, my goal is to display a Toast notification first with some additional information informing th ...

establish a connection with the node server and initiate the automatic mask detection feature

Here's my issue: I have a node server running a game I'm developing. The server listens on an IP address in the network, such as 192.168.x.x (which can vary). The game "frontend" is a web page hosted on a domain (like paperplane.io) that links ...

Trigger CSS transformations when a button is clicked

I have a form with a button on the left side and an image on the right side. When the user clicks the button, I want the image to rotate around its Y axis and display another div showing the result. Here is the code snippet: <div class="col-lg-4 co ...

sophisticated authorization structure for sails.js and angular

Thinking about developing some applications using sails.js and angular.js I'm in search of a way to create adaptable permissions. I want the ability to control permissions for model operations (CRUD) and functions within models. Additionally, it shou ...

Mastering Node.js: Writing to a Write Stream on the 'finish' Event

I'm currently using Node.js streams to process a text file line by line, apply some transformations, and then generate an SVG file based on the data. However, I am facing an issue where when I try to write the closing tag (</svg>) after all pro ...

Guide on declaring package.json during library publication in Angular 6

Building node modules using Angular6 should be a breeze. The Documentation outlines the following steps: ng generate library YOUR-LIBRARY ng build YOUR-LIBRARY --prod cd dist/YOUR-LIBRARY && npm publish By following these steps, a new project wi ...

I'm having trouble with the calculator, unable to identify the issue (Typescript)

I'm struggling with programming a calculator for my class. I followed the instructions from our lesson, but it's not functioning properly and I can't pinpoint the issue. I just need a hint on where the problem might be located. The calculat ...

Moving information from Ajax to PHP

I'm experiencing an issue with sending data from AJAX to PHP on the same site, "testpage.php". The PHP script doesn't seem to be displaying the data being sent. Using jQuery/Ajax: <script src="http://code.jquery.com/jquery-latest.js" type="t ...

Start by building a foundation project that incorporates Angular JS and CodeIgniter together

Currently diving into the world of AngularJS and I'm looking to set up a foundation code for building a website with AngularJS and Codeigniter. Does anyone have any sample projects that combine AngularJS and CodeIgniter that they could share? ...

Updating database records using AJAX in Laravel

In my project using Laravel, I need to update the status of a patient when they schedule an appointment with a doctor. The patient can have three statuses: Accept, Waiting (automatically set when the patient selects a date and time), Not Accept. However, w ...

a guide to incorporating Google Maps into your website using latitude and longitude coordinates

After retrieving a list of latitudes and longitudes from my API for an AngularJS application, I want to display a Google map indicating the positions of these coordinates. I attempted using an iFrame but it only displayed a blank page since the latitudes ...

The Javascript alert is displaying twice in Internet Explorer

My file validation function is set up to only allow the uploading of xls files, and it works properly by displaying an error message if a non-Excel file is uploaded. However, there is an issue with the alert firing twice in IE. Here is my code: function ...

Is it possible to create a column break within a CSS multicolumn design?

My text content sprawls over a CSS multicolumn layout with two, three, or four columns, utilizing CSS hyphenation. Sometimes, I want to terminate the text in one column early to allow the next paragraph to begin at the top of the next column. Is there a s ...

Vue encountered an unexpected issue: fn.bind is not recognized as a function

My Vue application structure is as follows: <template> <div id="app"> <home-central></home-central> </div> </template> <script> import HomeCentral from './components/HomeCentral'; export defau ...

Tips for adjusting image dimensions with url() method in css

I have successfully incorporated collapsible functionality on my page. I would like to display a down arrow image instead of the default '+' symbol on the right side of the collapsible section. To achieve this, I can use the following CSS code s ...

Control the options of the Select menu using ajax

Consider having two dropdown menus <select id=first> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</opti ...

Does anyone know of a way to integrate a calendar feature into a React application using a library

Greetings to everyone, I trust you are all enjoying a fantastic day. I am in search of an interactive calendar similar to this one for one of my applications https://i.sstatic.net/D3S3a.png Does anyone know of a React library that could assist me in crea ...

Access array information using AngularJS

Sorry for any language issues. I am trying to figure out how to extract an array data from AngularJS in order to save it using Node.js. This is my AngularJS script: angular.module('myAddList', []) .controller('myAddListController&apos ...

The combination of $watchCollection and multiple expressions is not effective

Having two arrays with boolean values, I attempted to use the $watchCollection function to trigger a message when changes occur in either array. However, it seems that the function is not working as expected. To diagnose the issue, please refer to this ex ...

Tips on using CSS to hide elements on a webpage with display:none

<div class="span9"> <span class="disabled">&lt;&lt; previous</span><span class="current numbers">1</span> <span class="numbers"><a href="/index/page:2">2</a></span> <span class="num ...