Steps to converting each new line into a list in JavaScript

Consider the following scenario where an object is structured as shown below:

data {
    second minute hour
    dog cat horse
    apple orange strawberry
}

Is there a way to iterate through the fields{} dictionary and convert each line into its individual array or list? The desired output format is demonstrated as follows:

data {
    [one: second, two: minute, three: hour]
    [one: dog, two: cat, three: horse]
    [one: apple, two: orange, three: strawberry]
}

Any thoughts on how this transformation can be achieved?

Answer №1

If you want to break the strings into individual words, you can use the split() method:

const data = [
    "second minute hour",
    "dog cat horse",
    "apple orange strawberry"
];
let result = [];
data.forEach(item => {
  let words = item.split(" ");
  result.push({
    first: words[0],
    second: words[1],
    third: words[2]
  });
});
console.log("Complete result:", result);
console.log("Specific part:", result[2].second);

Answer №2

The Syntax provided may not work, but there is a workaround by converting your data object into a string! (you can utilize template strings to include variables as well)

Check it out =>

const orange = "orange";

let data = ` {
second minute hour
dog cat horse
apple ${orange} strawberry
}`;

data = data.replaceAll('{', "");
data = data.replaceAll('}', "");
data = data.trim().split('\n');

let final_data = {};
data.forEach((val, index) =>  final_data[index] = val.trim().split(' '));
data = final_data;
final_data = {};
console.log(data);

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

There was an issue encountered while parsing the JSON Array

I have encountered an issue while trying to parse JSON data in my Android application : {"result":"success","source":"getPlayerNames","success":["Player1","Player2"]} My approach to parsing the data involves using a String called jsonData and implementin ...

Locate the index position of an element in one array based on a corresponding element in a

I am seeking a way to determine the index and group that an item belongs to within a parent json group. Is there a method for achieving this? I am willing to modify the json format if necessary. I made an attempt using JSON.stringify(), but it seems to be ...

Tips for showcasing content by hovering over buttons with the help of Bootstrap3 and Jquery

My code and fiddle are currently set up to display buttons when hovered over, but I want to modify it so that only the relevant button is displayed when a specific text is hovered over. For example, if "Water" is hovered over, only the button for Water sho ...

Encountering an Uncaught TypeError in Reactjs: The property 'groupsData' of null is not readable

While working on a ReactJs component, I encountered an issue with two basic ajax calls to different APIs. Even though I am sure that the URLs are functioning and returning data, I keep getting the following error message: Uncaught TypeError: Cannot read p ...

Creating a unique Nest.js custom decorator to extract parameters directly from the request object

I am working with a custom decorator called Param, where I have a console.log that runs once. How can I modify it to return a fresh value of id on each request similar to what is done in nestjs? @Get('/:id') async findUser ( @Param() id: stri ...

Add the current date plus 48 hours to the content on a webpage (JavaScript maybe?)

Hello there, I am currently in the process of setting up a small online store for a farm using Squarespace. One thing I would like to implement is specifying that items will be available for pickup two days after they are purchased online, instead of imme ...

The bootstrap table did not meet my expectations as I had hoped

I am currently using Bootstrap to create a basic two-column table similar to the one on the Bootstrap website here: http://getbootstrap.com/css/#tables. To achieve this, I have implemented a javascript function to display the table as shown below: $(&bso ...

Obtaining the correct information from an array using Ionic's Angular framework

I am currently working with an array of data that contains arrays within each item. I have been able to display the data as needed, except for the IDs. Approach Show arrays within the array Retrieve the IDs of the arrays (excluding the IDs inside the ar ...

What is the best way to extract a specific string that is nested within multiple arrays in a JSON file using PHP?

I am attempting to retrieve a string that is nested within multiple arrays. Although I have searched for examples, they all demonstrate how to retrieve a string from an array, not multiple arrays Json file: id: "<myid>" name: "<myname>" prope ...

"Critical issue: Meta tags are not present on the dynamic pages of the NextJS

In my NextJS application, the pages are structured as follows: App --pages ----_app.js ----index.js ----company.js ----users ------[userID].js I have a dynamic page named [userID].js that retrieves the userID through the router to display information for ...

What is the best way to disable the default sorting behavior when applying the unstack function in R?

One of the challenges I'm facing is with a list I created in R using the following method: alist <- as.list(unstack(DF, DF[,1]~DF[,2])) This approach utilizes unstack, which automatically sorts the keys alphabetically. The issue arises when later ...

What is the best approach to persuade VS code to recognize # as a comment within JSON files?

Special files are available that contain a combination of JSON data and # comments. It seems that enhancing Code's json.settings file with the following addition might be necessary: "files.associations": { "*.ourextension": "jsonc" } However, u ...

Tips for transferring a reference to a variable, rather than its value, to a method in VueJS

Within my template, there is this code snippet: <input @input="myMethod(myVariableName)" /> Following that, I have the myMethod function: myMethod(variablePassed) { console.log(variablePassed) } Upon execution, I receive the value of th ...

Is Firefox recording session storage information along with browser history?

When using Windows 10, I encountered a scenario where there is a server that accepts a POST to /random. Upon receiving the request, the server generates an HTML file with a new random number embedded in JavaScript. This JavaScript is responsible for displa ...

What is the best way to extract text from a list item in an unordered list (

I am trying to search a ul list that populates a ddSlick dropdown box. ddSlick adds pictures to list items, making it a visually appealing choice. To see more about ddSlick, you can visit their website here: Here is the code I am using to loop through the ...

Simulating npm package with varied outputs

In my testing process, I am attempting to simulate the behavior of an npm package. Specifically, I want to create a scenario where the package returns a Promise that resolves to true in one test and rejects with an error in another. To achieve this, I hav ...

Looking to parse and iterate over JSON data retrieved from a query using Express and Jade?

As a newcomer to nodejs, I am facing an issue with passing JSON data from a select query to the Jade view. Using Node.js Tools for Visual Studio and Express + Jade in my project, here is a snippet from my index.js file: exports.products = function (req, r ...

Tips for retrieving the text from a child element in a list with jQuery

I'm having trouble accessing the text of a child element within a list. I can only access the parent element and not sure how to get to the child element. Here is the HTML code: <ul class="nav nav-list"> <li class="active"> < ...

Tips for extracting value from a button inside a while loop in a modal

As I was working on my code, I encountered an issue with displaying pictures in a modal when a user clicks on a button. Here is the code snippet that I used to display the products and set up the session to store the selected picture for the modal. However ...

Is there a way to retrieve the current logged in user when working with socket.io?

When it comes to retrieving the logged in user using passport.js in most of my routes, it's a breeze - just use req.user.username. However, I've encountered an issue with a page that relies solely on websockets. How can I determine the username o ...