Creating an object property and assigning values dynamically with a for loop

Could someone please provide guidance on properly assigning values to object properties in this specific situation:

I am extracting the value from a text area, splitting it at each new line. My goal is to assign these split values to a property of an object within an array. The code snippet is as follows:

var items = [{}];

function process() {
    var i = 0;
    items.forEach((j) => {
        j.self = document.getElementById('input').value.split('\n');
    });

The function process() is triggered when a button is clicked.

When checking the console, I am seeing the following output:

https://i.sstatic.net/qLUtb.png

Instead of having multiple self values assigned to key[0] as an array, I want only one value to be stored for each key. Each split should be assigned to corresponding keys like key1.self, and so on.

The expected output would resemble something like this (though not entirely accurate):

items[0]{self: split-string[0]},
items[1]{self: split-string[1]},
items[2]{self: split-string[2]},

And so forth...

As opposed to what is currently displayed in the console:

items[0].self[0] = split-string[0];
items[0].self[1] = split-string[1];
items[0].self[2] = split-string[2];

If you understand the issue and have any suggestions, your assistance would be greatly appreciated.

Answer №1

It's a bit unclear what you're aiming for, but based on my understanding, you are looking to create an array of objects where each object has a property self that contains a line from the input.

If my assumption is correct, the following code should meet your requirements:

document.getElementById("clickme").addEventListener("click", processData);

function processData(){
    const items = document.getElementById("input").value
                           .split("\n")
                           .map(line => ({ self: line }));
    console.log(items);
}
<textarea id="input" rows="5">Line1
Line2
Line3
Line4</textarea>
<button id="clickme">Process</button>

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

Using AngularJS to differentiate between desktop and mobile devices, as well as determine if the connection is wifi or not

After some research on SO, I couldn't find similar Q&A about detecting connection types rather than just if a connection exists or not. The goal of my website is to automatically play a video clip based on the user's device and network statu ...

linking a div within a navigation bar

I have implemented a template from bootstrap. Here is the navigation bar where you can find the about section. Inside it, there is a bootstrap button: <button type="button" class="btn btn-light">Light</button> When I click on this button, the ...

The parameter is causing the Aggregate Function to malfunction

When fetching MongoDB data, I encountered an issue. Using the JavaScript parameter to retrieve data from MongoDB resulted in a null return, but manually typing it brought all the data without any problems. That part is working fine. const data = await Numb ...

A guide on managing multiple onClick events within a single React component

Including two custom popups with OK and Cancel buttons. Upon clicking the OK button, a review is composed. This review code is then sent to the server via a post request. Subsequently, the confirmation button reappears along with a popup notifying the user ...

Is there a way to efficiently compare two arrays and eliminate any duplicate entries that are already present in the second array from the first array?

How can I avoid duplicates when working with two separate arrays? I attempted to loop through arr1 while also looping through arr2, deleting matching values from arr1. def gmail_interviews arr1 = [] arr2 = [] arr1 = [{"from"=>"chinedu abalogu ...

Tips on calculating the combined value of price and quantity simultaneously

Greetings, kindly bear with me as my knowledge of JS scripting is quite limited. My expertise lies more in PHP programming. I stumbled upon this neat and straightforward script that calculates the total of product table rows and also provides the grand t ...

Troubleshooting Timeout Problems with Selebiun Crawler in C#

I am encountering an error while running the following code. public void GetCategoriesSelenium() { string javascript = System.IO.File.ReadAllText(@"GetCategory.js"); CrawlerWebSeleniumJS.ExecuteScript("var finished;"); ...

Utilizing array variables for storing data in localStorage without retaining previous values in React.js

Currently, I am struggling with how to efficiently utilize a single variable array for storing image URLs in local storage based on the user's current page. For example, if a user is on page 1 and adds images to that page, I need to save both the page ...

What is the most effective method for dynamically showcasing buttons in AngularJS?

Hello all, I'm currently learning AngularJS and I was wondering if anyone could recommend the simplest and most effective method for dynamically displaying links from AngularJS to HTML. I am looking to display a variable number of buttons in my HTML ...

rails failing to establish connection between dynamically added nested form and its parent

Currently, I have a form called 'tasks' and I am dynamically inserting another form called 'steps' as a child. The addition of 'steps' is handled by a javascript function that calls render('steps/form'). While the ...

Use jQuery's .each method to reiterate through only the initial 5 elements

Is there a way to loop through just the initial 5 elements using jQuery's each method? $(".kltat").each(function() { // Restrict this to only the first five elements of the .kltat class } ...

Utilizing Kendo Grid for client-side data paging

I am looking to utilize an MVC helper for constructing a grid on the server side, with the ability to dynamically add and remove rows on the client side. To achieve this functionality, I have implemented the following wrapper: @(Html.Kendo().Grid<SIGE ...

Sending multiple forms at once with a single submission

I've been racking my brain trying to determine the feasibility of a particular task. I am currently utilizing zen-cart as my shopping cart software, but what I really want to achieve is creating a hardcoded page featuring a list of 7-9 products. Each ...

Alter the hyperlink to a different value based on a specific condition

I need help with implementing a login feature on my app. The idea is that when the user clicks the login button, it should trigger a fetch request to log in with their credentials. If the login is successful, the button's value should change to redire ...

Ways to resolve the issue of receiving the error message "Uncaught ReferenceError: require is not defined" when

When attempting to use the readline function for input, an error is being displayed. What could be causing this issue? enter image description here const readline = require("readline").createInterface({ input: process.stdin, output: process.stdout, }) ...

Solving the AJAX POST Error 404 with the power of javascript, MySQL, and PHP

I want to build a dynamic search bar that fetches results from my database as I type in names. https://i.sstatic.net/P4GLs.png Here's the layout of my project: https://i.sstatic.net/y5svt.png The main files involved are map.js, where I handle the ...

Vue js lacks the ability to effectively link HTML elements to corresponding JavaScript functions

I seem to be missing a crucial element in my spring boot application. I am attempting to follow the initial steps outlined in the Vue documentation to create the most basic Vue application possible. Here is what I currently have: @Controller public class ...

Tips for iterating through nested objects with a for loop

Struggling with validations in an Angular 5 application? If you have a form with name, email, gender, and address grouped under city, state, country using FormGroupname, you might find this code snippet helpful: export class RegistrationComponent implemen ...

Mixing strings with missing slashes in links

console.log(mylink) When using the console to log mylink, the expected result is a normal link like http://example.com/something.jpg. I tried concatenating it as shown below: var html = '<div id="head" style="background:linear-gradient(rgba(0, 0 ...

Clicking a button in React requires two clicks to update a boolean state by triggering the onClick event

I have a React functional component with input fields, a button, and a tooltip. The tooltip is initially disabled and should only be enabled and visible when the button is clicked and the input fields contain invalid values. The issue I'm facing is t ...