Incorporating an extra parameter into an array using AngularJS

Currently, I am in the process of modifying some code and I need to introduce a new variable to an array. The initial code is functioning perfectly:

submit.addAttributeValue = function() {
    var aValue = submit.status.newAttributeValue;
    var aType = submit.status.selectedAttributeType;
    console.log('adding value', aValue, aType)
    if(aValue && aType) {
        submit.ProductMeta['attributes'][aType][aValue] = true;
    };
};

My intention was to include the variable 'aPrice' in the function:

submit.addAttributeValue = function() {
    var aValue = submit.status.newAttributeValue;
    var aType = submit.status.selectedAttributeType;
    var aPrice = submit.status.newAttributePrice;
    console.log('adding value', aValue, aType, aPrice)
    if(aValue && aType) {
        submit.ProductMeta['attributes'][aType][aValue][aPrice] = true;
    };
};

However, upon doing this, I encountered the following error:

Error: submit.ProductMeta.attributes[aType][aValue] is undefined
submit.addAttributeValue@http://dubdelivery.com/js/controllers-submit.js:369:13

Just to clarify, ProductMeta is initialized as: submit.ProductMeta = {};

Any suggestions on how I should proceed with this issue?

Thank You!

Answer №1

Your object is currently empty, which means you cannot assign a value to a nested field without first defining the parent field.

For example:

var obj = {};

In this case, you would need to set

obj.firstItem

before setting

obj.firstItem.secondItem

You can view a working example here

Answer №2

Check the debugger or simply log "aType", "aValue", and "aPrice". My guess is that "aValue" will be undefined.

Before manipulating object properties like this, ensure that the variables holding your property names are actually assigned values.

(By the way, with the advent of ES6 classes, it's generally not recommended to manipulate object properties/values in this manner).

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

There seems to be an issue with the CSV file, possibly indicating an error or the file may not be an SYLYK file when

After developing a node.js script to convert an array object into CSV format using the "objects-to-csv" library from NPM, I encountered an issue when opening the generated CSV file in WPS and Microsoft Office. The warning suggested that there was either an ...

Sharing objects between parallel states in Angular

Is there a way to seamlessly transfer a selected user from the details view to an edit view for parallel editing? In the details view, I capture 'selectedUser' and then need to make edits in specific fields within the edit view. There are two p ...

Using AJAX to submit a form with a file to Symfony results in $form->isValid returning false

Utilizing Angular JS code, I employ a method to submit a file and additional fields (along with a CSRF token) to a Symfony controller. var formObject = new FormData; formObject.append('email', self.careers[index].application.email); formO ...

Disable the cursor and prevent the user from entering text in a jQuery select box that has been styled with Chosen

Currently, I am employing the select box from HarvestHQ Chosen library. However, there is a problem where once an option is selected, I do not want the cursor to show in the box to prevent users from typing anything in it. Can someone please assist me in r ...

Utilize a filter function to sort through a React array and exhibit only the desired results

I've been attempting to filter an array in React Js, but unfortunately, I keep encountering an undefined error. My goal is to filter out images with a value lower than 10. The filtering code that I tried using is as follows: {this.images.filter((imag ...

Loading a three.js model with OBJMTLLoader and spinning it around

After successfully using the OBJMTLLoader class for one obj file and achieving proper rotation around a fixed point on the object with object.rotation.y -= 0.5, I encountered an unexpected issue when trying to replicate the same code with a different .obj ...

Having trouble resolving circular imports in your index.js file?

Consider the file structure given below: myFiles ├── index.js ├── getTrue.js └── dependentGetFalse.js Now, examine the following code snippets // index.js export { getTrue } from './getTrue' export { dependentGetFalse } from &a ...

Why is my `$http` data not being sent in Angular JS?

Within my controller, I am initiating an http request as shown below: var postData = { action: 'getTasksByProjectSlug', slug: 'inbox' } $http({ url: 'http://localhost/toodloo/api/kernel.php', method: 'POST' ...

javascript The event handler is not functioning properly for the dynamically loaded AJAX content

I am facing an issue with adding a JavaScript event listener to a dynamically loaded div via AJAX. Below is my code snippet: var QuantityMiniCart = function() { var infor = document.querySelectorAll( '.mini-cart-product-infor' ); if ( ...

Creating unit tests for a javascript method that employs a JWT token

Currently, I'm facing a challenge when writing unit tests in JavaScript for a method that includes JWT token validation. The method should only fetch results if the token is valid. I'm looking to mock the JWT token and return results. I've ...

Ways to recycle a function across various controllers

One of my challenges involves managing multiple controllers for various routes: app.controller('FirstController', function ($scope) { $scope.func = function () { console.log('route 1'); } } app.controller('SecondController ...

"An error is occurring in JavaScript: $ is not defined, but I am uncertain of the reason for it

I am attempting to test a code involving html, css, and javascript but it is not functioning as expected. I am unsure of the reason. click here to view image Create a random name generator with customizable input names and display the winner selected by t ...

Dealing with various menu states using Material-UI Menu component: Tips and Tricks

I've encountered an issue with my dynamically generated dropdowns and accordions that appear at the client-side render (based on validated user purchases from the database). The error seems to stem from my menu anchor element not being able to pinpoi ...

Navigating through a dropdown menu by utilizing the arrow keys

When hovering over the menu bar, the dropdown menus appear but I am unable to scroll down using the arrow keys. Clicking on a menu item also does not allow me to navigate through the menu with the arrow keys. It seems like this issue is related to the fo ...

The "useFindAndModify" option is not compatible

I am facing an issue connecting to my database using mongoose, and the console displays 'option usefindandmodify is not supported'. I am currently using mongoose version 6.0.0 Here is my code: mongoose.connect(constants.CONNECTION_URL, { ...

Maximize the sum of diverse numbers effectively

I have an array that contains objects structured like this: [ { "id": 91, "factor": 2, "title": "Test Product", "price": 50, "interval": 1, "setup": 0, "optional": false }, { "id": 92, "factor": 1, "title": "A ...

Decrease the jQuery version for a particular view exclusively

Imagine a scenario where I am utilizing jQuery version 1.10 in _Layout.cshtml, but need to downgrade to 1.7.2 for certain pages. Is there a way to achieve this without altering the Layout for these specific views? Can this be done at all? :) ...

I would like to store my json object in a text file so that my JavaScript code can access and read it from there. The goal is to efficiently utilize the file system for data retrieval within

Can someone please assist me with storing my JSON object in a text file and then reading it from that file using JavaScript? I am unsure about how to do this. Any help is appreciated. var objects = [{ "Object": { "ID": 1, &q ...

Scrolling horizontally to display dynamic columns based on a search query in AngularJS

I am facing a challenge with implementing search functionality in a table that has multiple dynamic columns with a horizontal scrollbar. The goal is for users to be able to search for a specific column name or data, and if a match is found, the scrollbar s ...

Looking to convert this single object into an array of objects within VueJS

So, I've encountered a bit of a pickle with the data from an endpoint that I need to format for a menu project I'm working on. It's all jumbled up and not making much sense right now. Any assistance would be greatly appreciated! This is the ...