JavaScript error: Attempting to assign a value to an undefined property, causing a TypeError

I keep encountering an issue with the following message: "Cannot set property '0' of undefined"

 var arrItems = {
    'product1': [],
    'product2': [],
    'product3': []
};

var temArr = {};
var dataFor = "";

function fnAddItem(elm, itemInd, rem) {

    if (elm != "" && elm != undefined) {
        var _name = $(elm).attr("data-name");
        var _id = $(elm).attr("data-id");
        var _in = $(elm).attr("data-index");
        itemInd = _in;

        *arrItems[dataFor][_in] = {
            'name': _name,
            'id': _id,
            'index': _in
        };*
        console.log(arrItems[dataFor][_in]);
    }

    var strHtml = "";

    $.each(arrItems[dataFor], function(key, value) {
        if (value['name'] != undefined || value['name'] != null)
            strHtml += '<div onclick="fnRemoveItem(this,0,\'' + dataFor + '\');" class="__selected_item" data-remove="' + value['index'] + '"><span>' + (value['index'] == 1 ? value['index'] : "") + value['name'] + (value['index'] == 3 ? value['index'] : "") + '</span><span class="x">&times;</span></div>';
        console.log(strHtml);
    });
}

Answer №1

It seems that you have forgotten to assign a value to the variable dataFor. When the code tries to access arrItems[dataFor], it returns undefined because dataFor='', resulting in arrItems[''] which does not exist.

To fix this issue, make sure to set dataFor to one of the 3 values available in the arrItems object.

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

Is there a way to open an HTML file within the current Chrome app window?

Welcome, My goal is to create a Chrome App that serves as a replacement for the Chrome Dev Editor. Here is my current progress: background.js chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('backstage.html', { ...

Decoding arrays in Delphi using the unserialize function

Is there a Delphi function similar to PHP's "unserialize()"? The string representation of my array is as follows: a:6:{s:15:"info_buyRequest";a:2:{s:3:"qty";i:1;s:15:"super_attribute";a:2:{i:234;s:4:"2047";i:237;s:4:"4312";}}s:15:"attributes_info" ...

Incorporating an external library into a Node.js virtual machine

I'm currently working on a nodejs library that enables users to write and execute their own JS code. Here is an example: var MyJournal = Yurnell.newJournal(); module.exports = function(deployer) { MyJournal.description = "my first description& ...

Minimize the length of the styled-component class name in the upcoming iteration

Dealing with styled-components in Next along with React can pose a challenge when it comes to ensuring proper rendering of the styled components. To tackle this issue, Next offers the compiler.styledComponents flag within the next.config.js file like so: c ...

The comparison between StrictNullChecks and Union Types in terms of syntax usage

Understanding StrictNullChecks in TypeScript Traditionally, null and undefined have been valid first class type citizens in JavaScript. TypeScript formerly did not enforce this, meaning you couldn't specify a variable to potentially be null or unde ...

Challenges faced when subscribing to global events in JavaScript

I have some questions about the JavaScript code snippet below: What does .events.slice(-1)[0][0] signify? Similarly, could you explain the purpose of nodes_params += "&ns=" + GLOBAL_EVENT + "," + start_from + ",-,-";? Could you elaborate on what is m ...

Issues with the functionality of the submit button (html, js, php)

Seeking assistance with a submit button functionality issue - I have a simple submit button that allows visitors to enter their email address. Upon clicking the button, it should add their email to a CSV file and display a pop-up thank you message. The pr ...

choosing from dropdown menu items

Learn HTML <table> <tr> <td>ENTER PRINCIPLE AMOUNT</td> <td><input type="text" name="principle" size="7"></td> </tr> <tr> <td>ENTER RATE OF INTEREST</td> <td><input type="text" na ...

Guide to importing a JavaScript module as any type without using a declaration file (d.ts)

Looking to bring a js module into my ts app. Is there a way to achieve this without creating a d.ts file? If not, how can it be declared as any in the d.ts file? Currently using //@ts-ignore to ignore the error. Appreciate any help! ...

Tips for creating a Vue component that triggers the select dropdown to open when the entire div or wrapper is clicked

I have a custom-designed select dropdown with unique symbols for the select arrow. To achieve this look, I've hidden the default select arrow/triangle and placed our symbol on top as an image file. <div class="select-wrapper"> < ...

How to effectively implement addEventListener() / attachEvent()?

Can anyone provide guidance on how to correctly use addEventListener and attachEvent? window.onload = function (myFunc1) { /* do something */ } function myFunc2() { /* do something */ } if (window.addEventListener) { window.addEventListener('load ...

Is it false to say that false in Javascript is still false?

After conducting some research, it appears that the question I have in mind has not been asked before, or maybe it has slipped under my radar. A rational approach would be to consider the following logic: false && false === true false && true === false t ...

Improving Performance in AngularJS Through Efficient Scope Passing Between Controllers

I am facing a situation in my AngularJS project where I have two controllers - controller 1 is constantly present in the view, while controller 2's visibility can change based on the view. In order to ensure that controller 1 has access to certain sco ...

How to display only a portion of content using UI Bootstrap collapse feature

In my Angular.js application, I currently have a row of buttons that open up new routes to display partial views. Now, I need to modify some of these buttons to trigger a ui.bootstrap Collapse feature with the view inside it. The template code from the ui. ...

When it comes to mapping routes in the express framework of Node.js

Currently, I am facing an issue while setting up the route in my app.js file. The route for the listing of flights is passed in the routes/flights.js file. When I define the route at the bottom of all routes, it results in a 404 error. However, if I place ...

The functionality of nested dynamic routing in the API is experiencing issues

Looking to extract product details from a specific category of products? My folder structure appears as follows: https://i.stack.imgur.com/1UCy3.png In "productId/index.jsx" => This snippet is utilized to retrieve individual product details: ...

Difficulties with efficiency in Finite difference technique

Utilizing the finite difference method in a piece of C code to estimate values has revealed that an iterating function, iterate(), is slowing down the process. There seems to be inefficiencies in the current implementation of this averaging method. void i ...

`Multiple Autocomplete feature that allows rendering of previously selected items`

I've encountered a slight issue with my autocomplete feature. On the same page, I have two different autocompletes set up. Both of them pull elements via ajax from separate sources and use the _render option to display the items. The problem arises wi ...

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" ...

How can I utilize angular's $http service to fetch a JavaScript file?

I've been exploring the integration of Angular with Node.js and attempting to establish a connection to a MySQL database. Within my script (server.js), I am utilizing the node mysql module as shown below: var mysql=require('mysql'); var ...