Ways to add elements to a non-existent index in an array

I am facing an issue while attempting to form sets of objects in an array and generating a new set if the item is not already present.

The structure of the data looks something like this:

[
  {
    "order": orderData,
    "items": itemData
  }, {
    "order": orderData,
    "items": itemData
  }
]

However, when I try to create a new array index dynamically and attempt to add items to it, I encounter the error below:

Cannot set property 'items' of undefined

In the scenario, setNo = 2, but this.cart[2] has not been initialized yet.

this.cart[setNo]['items'].push(items);

How can I properly initialize this index so that items can be added to it dynamically?

Answer №1

It's important to verify before proceeding:

if (!this.cart[setNo]) {
   this.cart[setNo] = {order: {}, items: []};
} 
this.cart[setNo]['items'].push(item);

Answer №2

If the cart[setNo] does not exist, create an object with the items property.

if(!this.cart[setNo]) this.cart[setNo] = {items:[]};
this.cart[setNo]['items'].push(items)

Answer №3

Another approach could involve utilizing the conditional (ternary) operator to validate and update the values:

let array = [
  { "status": {}, "data": [] }, 
  { "status": {}, "data": [] }
], index = 2

array[index] 
  ? array[index]['data'].push(1) 
  : (array[index] = { status: {}, data: [] })['data'].push(1)

console.log(array)

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

Experiencing difficulties with certain npm CLI modules when using it as a task runner and build tool

After coming across an article about using npm as a build tool, I decided to give it a try for my tasks. However, I am facing an issue that has me stuck. Whenever I run a global command-line tool like JSLINT, JSHINT, or ESLINT using npm, the console always ...

Get the image resolution at the same time

I need a function that can take a URL pointing to an image as a parameter and synchronously provide the resolution of that image. The function should pause execution until the image is fully retrieved. Here is an example of what I'm looking for: func ...

What is the best way to trigger a JavaScript onclick event for a button that is located within a dropdown menu on an HTML page

I've implemented a feature that resizes the font size within a text area based on the selected font size. It was functioning flawlessly... until I decided to place the font size selection in a drop-down menu, which caused the feature to stop working. ...

Ensuring the successful execution of all AJAX calls (not just completion)

I've seen this question asked many times about how to trigger a function once all AJAX calls have finished. The typical solution involves using jquery.stop(). However, my situation is unique - I want to display a confirmation banner only after all AJA ...

Breaking an array into parts using regular expressions and references

I'm trying to split a string by commas, but I need to ensure that commas inside square brackets are not included. For example, consider the following string: '"f2140202585",true,"some, str","numeric","MegapixNum","","","0.3,16.0","0.3,16","17",2 ...

The source 'http://localhost:3000' is not authorized to access the Twitter API

I am working on a web application that utilizes the Twitter API REST. On one of my pages, I have a list of Twitter accounts and a button to add a new account. When this button is clicked, it triggers a function in the Angular controller: // Function to ...

Determining the top element displayed in a div: A guide

Looking for an answer on how to determine the top visible element while scrolling? You may find some insights in this post: (Check if element is visible after scrolling). My scenario is slightly different - I have a scrollable div containing multiple ele ...

Get the PDF in a mobile app using HTML5 and Javascript

For my HTML5/JavaScript-based mobile application, I am in need of implementing a feature that enables users to download a PDF file. The PDF file will be provided to me as a Base64 encoded byte stream. How can I allow users to initiate the download proces ...

Executing numerous xhttp.send requests within a single webpage

Hey there, I'm facing an issue with xhttp.send(); as it keeps giving me the error message net::ERR_EMPTY_RESPONSE Here is a snippet of my code. Whenever a user clicks too quickly, they get kicked off the page. Is there a way to prevent this? docum ...

What is the method to conceal an element after detecting and locating a specific class using jQuery?

Can someone please assist me today with the following task: Step 1: <div id="htmlData"> <div class="col-md-12"> <div class="pull-left"> <h3>Report: <strong>Travel </strong></h3> ...

Utilize $validators during blur/focus interactions

In my validation directive, I currently manually set the validation state like this: $element.on('focus', function() { $scope.$apply(function() { ngModelCtrl.$setValidity('length', true); }); }); $element.on('blu ...

Find the sum of every combination of numbers in the array

I've reviewed my code countless times and I'm stumped by the issue. My code is designed to calculate all possible sums of numbers within an array. It works perfectly when there are only 3 numbers in the array, but once I add a fourth number, it i ...

In JavaScript, utilize an object that is defined outside of a function

Here is a JavaScript function I have: function status(){ this.functionA = function(){} //Other functions and fields go here } Now, there is another function as well: function create(root){ var server = library(function (port) { //Additional functi ...

Error in jQuery when trying to access the src attribute of an image: "undefined src

Just started delving into jQuery. I'm trying to grab the image source and showcase it in a fixed division like a pop-up, along with the image title. However, I'm encountering difficulties in fetching the image source. My attempt with the .attr() ...

Getting the dimensions of an image using a path in JavaScript

I am trying to display a div with an image, its name, size, and download link using jQuery. Here is the code I have created: var image = 'image/example.png' $('#download').attr("href", result2); $('.image').attr("src", re ...

There was a TypeError that was not caught in the promise, stating that the function window.showOpenFilePicker is not valid

Encountering TypeError with File System Web API While experimenting with the File System Web API, I keep receiving a TypeError stating Uncaught (in promise) TypeError: window.showOpenFilePicker is not a function. I am unsure of what is causing this issue. ...

Encountered an issue while compiling code using the Istanbul plugin

I'm currently working on generating a code coverage report for my ReactJS project using the babel-istanbul-plugin. However, when I incorporate "istanbul" as a plugin in my .babelrc file and attempt to build, I encounter the following error: ERROR in ...

Is it best practice to contain all side effect logic within useEffect in React?

I am looking to monitor user clicks on a button and send the data to the server. I am considering where to implement the logic for "sending the data to server" within my component. Should I include it inside the onClick handler or should I move it to use ...

Vue component fails to react to updates from Vuex

Currently, I am developing a system to facilitate the management of orders at a shipping station. Although I have successfully implemented the initial changes and most of the functionality, I am encountering an issue where one component fails to update ano ...

jqGrid: What could be causing the events I defined for grid edit to not fire?

I've been attempting to make in-line edits on a grid, but it seems like none of the events connected to those edits are being triggered. I am specifically looking to use afterSubmit: so that it triggers after the user has edited the Quantity field in ...