Guide to utilizing various Nodelists using the forEach function

I'm currently developing an online store project that includes a shopping cart feature. My goal is to send a POST request to the server with the items selected by the user in the cart. I have initialized an empty array and I have 3 Nodelists containing product information. What I aim to do is extract their values, text content, and dataset properties, then nest them all within my empty array like this:

var products = { Lines: [ ] };

This is what I have attempted so far:

const prName = this.parentNode.parentNode.querySelectorAll('.product-name-link');
const prInput = this.parentNode.parentNode.querySelectorAll('.product-quantity-input');
const prPrice = this.parentNode.parentNode.querySelectorAll('.product-price-total');

prName.forEach(product => products.push(product.dataset.id))
prInput.forEach(product => products.Lines.push(product.value))
prPrice.forEach(product => products.Lines.push(product.textContent))

The desired outcome should resemble something like this:

"Lines":[
    {
     "Assortiment":"1627aea5-8e0a-4371-9022-9b504344e724",
     "Quantity":12678967.543233,
     "SalePrice":12678967.543233,
     "Warehouse":"1627aea5-8e0a-4371-9022-9b504344e724"
    },
    {
     "Assortiment":"1627aea5-8e0a-4371-9022-9b504344e724",
     "Quantity":12678967.543233,
     "SalePrice":12678967.543233,
     "Warehouse":"1627aea5-8e0a-4371-9022-9b504344e724"
    },
    {
     "Assortiment":"1627aea5-8e0a-4371-9022-9b504344e724",
     "Quantity":12678967.543233,
     "SalePrice":12678967.543233,
     "Warehouse":"1627aea5-8e0a-4371-9022-9b504344e724"
    }
    ],

Answer №1

After carefully considering the various points raised in the comments, a potential solution could be structured like this:

const inventory = { Items: [] };

const itemName = this.parentNode.parentNode.querySelectorAll('.item-name-link');
const itemQuantity = this.parentNode.parentNode.querySelectorAll('.item-quantity-input');
const itemPrice = this.parentNode.parentNode.querySelectorAll('.item-price-total');

// Iterate through each item to create a product entry...
itemName.forEach((element, index) => inventory.Items.push({
  Name: element.dataset.id,
  Quantity: itemQuantity.item(index).value,
  Price: itemPrice.item(index).textContent
}));

Answer №2

Enclose the elements using Array.from() like this:

Array.from(elements).forEach( function(item) {
    console.log(item);
});

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 character variables as input for functions in R with the Tidyjson package

Exploring the functionalities of the tidyjson package (latest version from GitHub, created by Jeremy Stanley), I set out to automate the search and extraction of nested arrays. The examples provided below demonstrate the desired output. '{"name": {"f ...

Using JavaScript and HTML to show the current month, date, and year on a webpage

I am looking to display not only the time, but also the month, date and year. My attempted solution involved creating variables for the month, day and year, and then using getElementById. Here is an example of what I tried: var d = date.getDay(); var mn ...

Using Vue.js to share events and data across various components

I am currently working on an application that features a Google map with a places autocomplete controller, similar to the example provided by Google at this link. Whenever an address is searched or selected, or when the map bounds are changed, I trigger a ...

Storing a reference to children generated by a function within a child prop

I am currently working on a Feed component that accepts a data prop, consisting of an array of items, and a children prop intended for a function that maps the data to a DOM element. My current challenge is implementing the ability to scroll to any elemen ...

Using a variable as a parameter when requesting a value from a JSON object in JavaScript

I consider myself to be at an intermediate level in JavaScript, but I've hit a roadblock when trying to access the key in a JSON message that is returned to me. My code is dynamic, so I need to pass the key into the query. For example: After running ...

I have implemented a button in PHP and now I am looking to invoke a function when that button is clicked

I have a PHP-generated HTML button and I'm having trouble calling the mybtn3() function when it is clicked. The button code looks like this: echo"<td width=14% align=center><input type=button value=Export onclick=mybtn3() /></td>"; ...

Developing a JSON structure from a series of lists

var data = [ [ "default_PROJECT", "Allow", "Connect", "Allow", "AddComment", "Allow", "Write", "Allow", "ViewComments", "Allow", "ExportData", "Allow", ...

Passing data from a parent node to a child node using JavaScript and the D3.js library

Creating a legend (var legend) for my d3js chart involves binding data to the parent 'g' element, specifically a string (label) that is needed in the child 'text' element. Any ideas on how to assign the parent data from the 'g&apo ...

Can a static text be displayed randomly using Javascript?

What I'm searching for is a unique text display feature that's different from scrolling. I envision a subtle fade in/out effect, but it's not necessary. The main goal is to fit within a small area on a website with limited vertical space - ...

Encourage users to activate the physical web feature in compatible web browsers

Is it possible to use JavaScript to encourage users to activate the physical web (and thus BlueTooth), similar to how APIs like "getUserMedia()" prompt users? UPDATE: Given that this technology is still in its early stages and not extensively supported, t ...

Upgrade your function to utilize Firebase V9 with Next.js framework

I recently updated my project to use version 9 of firebase, and since then, I've been encountering some code errors that I'm struggling to resolve. The previous function had the following structure, but now I need to update it to work with the n ...

Using <span> tags to wrap sentences within <p> tags while maintaining the rest of the HTML formatting

In order to achieve my goal, I have utilized the following code to extract content within tags and encapsulate each sentence in tags for easier interaction. $('p').each(function() { var sentences = $(this) .text() ...

Is the use of addEventListener("load",... creating an excessive number of XmlHttpRequests?

Consider a scenario where you have the following JavaScript code running in a Firefox plugin, aimed to execute an XmlHttpRequest on a page load: function my_fun(){ var xmlHttpConnection = new XMLHttpRequest(); xmlHttpConnection.open('GET', ...

The disappearance of a Python numpy mask when assigning an array to another array

Currently, I am working with geodetical data and using masks to cover areas without data. One issue I encountered involves designing an array with different time series data for various locations on the earth. The problem arises when I assign separate spot ...

Iterate through the JSON data values using a loop and showcase each one by presenting them in individual cards

I'm having trouble determining which type of loop to use in this situation because I am still learning jQuery and JS. On the result page, I have set up cards to separate each piece of data from the JSON file, but I am unsure how to actually display th ...

I am unable to transfer information retrieved from the fetch call to the express API

I'm facing a puzzling issue that has me stumped - I have code that should be working, but it's not. const getPhones = async () => { await fetch(url, requestOptions) .then((response) => response.text()) .then((XMLdata) => { ...

Creating dynamic variable names in Jquery by combining strings and numbers

Hey there, I'm really stuck and in need of a solution for the issue I've encountered. Currently, I have a script that sends an Ajax GET request and retrieves JSON data. The data is successfully returned, but when I try to loop through it, that&a ...

The latest value has replaced the state's previous value

In my current function, I am updating an array stored in state based on the status of 9 tables. Each table calls this function to check its status, and if true, it is added to the array. const [projectSpaceTypeWarning, setProjectSpaceTypeWarning] = useSta ...

Utilizing an SSL certification (pem file) within JavaScript

Currently in the process of developing a program to extract data from the FAA's AIDAP database. I received a security certificate in the form of a .p12 file, which I have successfully converted into a .pem file. However, I am encountering difficulties ...

Parsing JSON data using Newtonsoft.Json library to convert it into a List collection with named entries

I need help deserializing this JSON data set: { "Home1": [ { "name": "Hans", "age": 20 }, {...} ], "Home2": [ {...}, {...} ] } I want to map it into a collection of ...