Adding strings to an array according to the numerical value entered in an input field using JavaScript

Can we dynamically add a string to an array based on the quantity entered by the user in a field?

For example, if a user adds an item to their shopping basket, the function() will add the SKU string to the array. However, if the user then updates the quantity of the item in the basket (e.g. changes it to 5), should we push 5 SKU strings into the array?

Is this feasible?

I initially tried using a unary operator to convert the string to a number in the code snippet below, but it seems to return NaN likely due to the fact that skuField is a string

For example: SKU 321005Y-00100-ITM

console.log('Pushing SKU based on qtyField ', [item.qtyField + (+item.skuField)]);

Object example: This is how my object appears when an item with a quantity of 3 is added to the basket.

var updateCartItem = {
    Products: [
  {  
       "product_idField":"96031",
       "skuField":"321005Y-00100-ITM",
       "nameField":"Cooper Sunglasses",
       "priceField":"75.0000",
       "qtyField":3,
       "qtyFieldSpecified":true,
       "$$hashKey":"object:8"
    }
 ]
}

Code snippet:

for (var i = 0; i < updateCartItem.Products.length; i++) {
     var element = updateCartItem.Products[i];
  console.log([element.skuField]) // this will only push 1 sku (should be 3)
}

Therefore, based on qtyField: 3, I anticipate having

["321005Y-00100-ITM", "321005Y-00100-ITM", "321005Y-00100-ITM"]
. If qtyField is 5 or 100, then the array string should contain the same number of SKU strings as the quantity specified.

Answer №1

It seems like you're wondering about using a string as an index in an array. In JavaScript, you cannot directly use a string as an index in an array, but you can use an object instead. Objects in JavaScript can be thought of as "arrays with String indexes." For example:

var objectArray = {"321005Y-00100-ITM": 1};

is equivalent to:

var objectArray["321005Y-00100-ITM"] = 1;

If you need to update the quantity, you can simply assign a new value to the corresponding key in the object:

var objectArray["321005Y-00100-ITM"] = 5;

Hopefully, this clarifies things for you.

Answer №2

I'm not entirely certain if this aligns with your requirements. I have included two additional products: the first one has a quantity of 3 (as per your example), the second has a quantity of 1, and the third one has no specified quantity (a personal addition).

To facilitate this, I have implemented a function called getArrayFrom(...) (feel free to rename it) which generates an array of the skuField names based on the provided qty value.

var updateCartItem = {
    Products: [
  {  
       "product_idField":"96031",
       "skuField":"321005Y-00100-ITM",
       "nameField":"Cooper Sunglasses",
       "priceField":"75.0000",
       "qtyField":3,
       "qtyFieldSpecified":true,
       "$$hashKey":"object:8"
    },
      {  
       "product_idField":"another",
       "skuField":"another-ITM",
       "nameField":"Pony Sunglasses",
       "priceField":"75.0000",
       "qtyField":1,
       "qtyFieldSpecified":true,
       "$$hashKey":"object:8"
    },
    {  
       "product_idField":"empty",
       "skuField":"empty-ITM",
       "nameField":"Nobody wants it Sunglasses",
       "priceField":"75.0000",
       "qtyField":0,
       "qtyFieldSpecified":true,
       "$$hashKey":"object:8"
    }
 ]
}

function getArrayFrom(product) {
    const arr = [];
    if (product && product.qtyField) {
        for(var i = 0; i < product.qtyField; ++i) arr.push(product.skuField);
    }
    return arr;
}

for(var i = 0; i < updateCartItem.Products.length; ++i) {
    var element = updateCartItem.Products[i];
    console.log('product: ' + element.nameField + ' has array ', getArrayFrom(element));
}

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

`Optimizing Performance using jQuery Functions and AJAX`

As someone exploring ajax for the first time, I'm eager to learn how to write jQuery code that ensures my simple functions like slideshows and overlays still work smoothly when a page is loaded via ajax. Currently, I am implementing the following met ...

Getting the id of a single object in a MatTable

I'm currently working on an angular 8 application where I've implemented angular material with MatTableDatasource. My goal is to retrieve the id from the selected object in my list: 0: {id: "e38e3a37-eda5-4010-d656-08d81c0f3353", family ...

Troubles arising when trying to import a CSS file into a React Component without resorting to

https://i.sstatic.net/fNEuU.png After exploring the latest version of create-react-app, I discovered that there is no need to use the "npm run eject" command. When I tried that in the past, I struggled to locate the webpack.js file for modifications. htt ...

Exploring the concept of making nested API requests within a route using Node.js and

Being a newbie in the world of coding, I'm excited to make my first post here. My current learning project involves developing a website that utilizes an external CRM for storing client data received from web forms. The storage functionality is up an ...

Search for an element deep within a tree structure, and once found, retrieve the object along with the specific path leading to

I created a recursive function to search for a specific object and its path within a tree structure. However, when I changed the target ID (from 7 to 10) in the function, I encountered an error: "message": "Uncaught TypeError: Cannot read ...

Displaying AJAX data in Django using an HTML table

My Django template currently has the following AJAX script running: function create_table() { $.ajax({ method: "GET", url: "/api/data/", success: function(data){ console.log('button clicked') ...

I am looking to eliminate any special characters from a designated section of a string using Javascript

I have a string that looks like this: var myString = '{"key1":"value1", "key2":"value2", "key3":"value3"}'; My objective is to remove double quotes and other special characters only from value3. Sometimes the string may look like: var myStrin ...

Developing Functions using MongoDB Console

When running the query db.graduates.find({student_id: '2010-01016'}).pretty(), it returns a result. Afterwards, I created a function: function findStud(name,value){ return db.graduates.find({name:value}); } However, while executing findStud("s ...

The random quote generator or current tweet quote feature is malfunctioning

I am having trouble with a jQuery on click function that is not working to tweet the current quote. I am working on building a random quote machine and tweeting the current quote is essential. Despite successfully implementing the JSON API, I cannot seem t ...

Tips for utilizing createTextNode in JSDOM

When attempting to create a UI test for an HTML element using Jasmine and jsdom, I encountered an issue. Within my component, I utilized the createTextNode function to populate the content of the DOM element. Unfortunately, during testing, the document.c ...

Guide to capturing mouse drag coordinates using JavaScript within a JSP page

My task is to record the starting coordinates (x,y) and ending coordinates (x,y) of a mouse event. For example, on an HTML page with an image, users should be able to select a specific area by dragging the mouse. Therefore, I need to capture the coordinat ...

Error encountered when attempting to export a TypeScript class from an AngularJS module

In my application using Angular and TypeScript, I have encountered a scenario where I want to inherit a class from one module into another file: generics.ts: module app.generics{ export class BaseClass{ someMethod(): void{ alert(" ...

Encountering a React JS error with Admin on Rest while making an API request

When making an API call (GET) with React.js using Admin on Rest, I encountered an issue. The server returns data when calling localhost:5001/cities, but there seems to be an error on the client side as indicated by the browser log: failure.js:18 Error: Th ...

Retrieve the attribute value from an HTML element in a JSON response using JavaScript

I received a JSON request result containing a blogger post. // API callback posts( { "version": "1.0", "encoding": "UTF-8", "entry": { "title": { "type": "text", "$t": "Vimeo Embed Video Post" ...

Developing a pop-up feature that triggers upon clicking for a miniature rich text editing

Looking to integrate the Tiny rich text editor into my code. Check out the TextEditor.js component below: import React from 'react'; import { Editor } from '@tinymce/tinymce-react'; class App extends React.Component { handleEditorCha ...

Discovered an issue with AngularJS involving ng-show and ng-if?

Upon my investigation, I have identified multiple issues with angularjs: <div ng-show="['[]']">this should be displayed but it is not working as expected</div> <div ng-show="[]">this should be displayed but it is not working as ...

How to retrieve a nested array element in JavaScript

Here is the Pastebin link of the index.html file for reference: http://pastebin.com/g8WpX6Wn (The file contains broken image links and no CSS styling). If you would like to access the entire project, you can download the zip file. I am currently working ...

What is the most effective method in Vue.js for transitioning elements without the need to use v-for and v-if at the

Utilizing v-for to generate multiple <p> elements, each one animating in within a Vue <transition> component if the v-if condition is met. Below is the code snippet: <transition name="fade"> <p v-for="(quote, idx) in game.quot ...

CSS classes designed to mimic JavaScript object attribute-value pairs

I stumbled upon some interesting css class-value combinations within HTML tags. It seems like a specific JavaScript code is interpreting this, but it's something I haven't encountered before. I came across this on www.woothemes.com/flexslider/ (y ...

Why is JavaScript globally modifying the JSON object?

I have a few functions here that utilize the official jQuery Template plugin to insert some JSON data given by our backend developers into the variables topPages and latestPages. However, when I use the insertOrHideList() function followed by the renderLis ...