Unable to store object data within an Angular component

This is a sample component class:

export class AppComponent {

  categories = {
     country: [],
     author: []
  }

  constructor(){}

  getOptions(options) {
     options.forEach(option => {
        const key = option.name;
        this.categories[key].push(option.value);
     })
  }
  
}

When a button is clicked, the getOptions(options) function is called from a different component. The structure of the options object is as follows:

options = [
  {name: 'country', value: 'Germany'},
  {name: 'author', value: 'Franz Kafka'}
]

As a result, the values of this.categories are updated like so:

this.categories[country] = ["Germany"]
this.categories[author] = ["Frank Kafka"]

Each time the button is clicked, the value of options changes. However, when new values are sent for options such as:

options = [
  {name: 'country', value: 'Japan'},
  {name: 'author', value: 'Masashi Kishimoto'}
]

The old value for this.categories[country] does not get saved. The expected new value for this.categories[country] should be ["Germany", "Japan"], but it is only ["Japan"].

Answer №1

It appears that the code is not functioning correctly, even after attempting to troubleshoot with Javascript. One suggestion would be to verify the truthy value of options.value. It's possible that there may be some entries without a corresponding value.

let categories = {
     genre: [],
     artist: []
  }
  
let options = [
  {name: 'genre'},
  {name: 'artist', value: 'Vincent Van Gogh'},
  {name: 'genre', value: 'Romance'},
  {name: 'artist', value: 'Leonardo da Vinci'}
]

options.forEach(option => {
        const key = option.name;
        console.log(key);
        if(option.value)
        categories[key].push(option.value);
     })
     
console.log(categories);

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

AngularJS controller encounters a scoping problem within a callback function

I have created an angular application with a simple login form that can be viewed on this JSFiddle. HTML Code: <form data-ng-app="jsApDemo" data-ng-controller="loginCtrl"> <label for="username">Username:</label> <input type=" ...

Tips for implementing self-managed state in Vue.js data object

My approach in organizing my Vue application involves using classes to encapsulate data, manage their own state (edited, deleted, etc), and synchronize with the back-end system. However, this method seems to conflict with Vue in some respects. To illustra ...

What is the best way to access the input element of ng-content from the parent component?

Creating a unique component in the following structure <div class="custom-search-field" [ngClass]="{'expanding': expanding}"> <ng-content></ng-content> </div> When using this component, users are expected to include ...

Access real-time information via JSON

I am facing a logical thinking challenge. Successfully retrieving data from a PHP file via JSON, but now encountering a slight issue. My goal is to retrieve various headlines - main and sub headlines. Each main headline may contain an unknown number of su ...

IE11 is throwing an error due to an unexpected quantifier in the regular expression

I have a string like SHM{GHT} and I need to extract the value from within the curly braces (GHT in this case). I used RegExp successfully to do this, but encountered an issue when testing on Internet Explorer. The page broke and I received an error message ...

What could be causing my mongoose array to remain empty without any values being stored in it?

Issue at Hand While I have come across several similar problems on Stack Overflow about this particular issue, none of the solutions provided seemed to work for me. I am in the process of developing a basic Forum application with two routes - one for cre ...

Having trouble deploying a Heroku app using Hyper? Here's a step-by-step guide to

After running the following commands: https://i.stack.imgur.com/WZN35.png I encountered the following errors: error: src refspec main does not match any error: failed to push some refs to 'https://git.heroku.com/young-brook-98064.git' Can anyon ...

Loading an external npm package in Angular 8

I am facing an issue with importing the dragscroll.js package. I have attempted to import it in both the index.html file and angular.json file but keep getting this error message: dragscroll.js:1 Failed to load resource: net::ERR_FILE_NOT_FOUND My project ...

Select multiple options by checking checkboxes in each row using React

Is it possible to display multiple select checkboxes with more than one per row? For example, I have four options [a, b, c, d]. How can I arrange it to have 2 options per row, totaling 2 rows instead of having 1 option per row for 4 rows? ☑a ☑b ☑c ...

The 'ref' attribute is not found within the 'IntrinsicAttributes' type

I'm currently working on a TypeScript project using React. Although the code is functional, I keep encountering compiler errors with my ref. Here's an example of the code: Firstly, there's a higher-order component that handles errors: expor ...

Is there a method in AngularJS to submit form data when the input fields are pre-populated using a GET request?

How do I submit form data in AngularJS? I have a div that populates the input field from a GET request. Now, I want to send this data using a POST method. How can I achieve this? Below is the form div: <div class="row" ng-app="myApp" ng-controller="myC ...

A guide on defining global TypeScript interfaces within Next.js

In the process of developing an ecommerce web application with next.js and typescript, I found myself declaring similar interfaces across various pages and components. Is there a method to create global interfaces that can be utilized by all elements wit ...

Exploring smooth scrolling functionality using AngularJS and integrating it with IFrames

After implementing an angular controller, I included the following code: angular.element(document).ready(function () { ... } Within this setup, I added a function to enable smooth scrolling to the hash of window.location.hash using .animate({scrollTop... ...

Does property binding truly function as a one-way binding mechanism?

Recently, I began diving into Angular tutorials and came across an interesting point about Angular property binding. It seems that in this particular case, Angular property binding is a one-way binding, meaning that changes to the property of HeroComponent ...

To handle the input field efficiently in Angular, consider utilizing two <input type="radio"> elements

I am facing a challenge in my Angular 5 project where I have two radio buttons and need to dynamically update the value of formControlName and placeholder for an input field based on the selected radio button. How can I tackle this issue? <div clas ...

Looking to adjust the background-image size of a table cell (td) upon clicking a specific

I have a website where I would like to display logos of different games with links attached to them. I have managed to adjust the size of the image on hover, but now I am looking for a way to keep the size bigger after clicking on the link. Is there a simp ...

Using AJAX and PHP to dynamically fill HTML drop-down menus

In order to populate the DropDown controls on my HTML Form dynamically, I have implemented a code that utilizes AJAX to make a call to a .php file. This .php file is responsible for filling the DropDown control with values from a single column. Throughout ...

Retrieve files from Amazon S3 using JavaScript

I'm currently working with a javascript file that's intended to download a text file from one of my S3 buckets. However, after running this file using "node file.js", nothing happens and there's no output. Is there something I'm missing ...

Using JavaScript to set attribute values in Python Selenium, these values are cleared after each update

Assuming : for i in list('{}'.format(value)): self.browser.execute_script( "arguments[0].setAttribute('value', '{}');".format(i.replace('&b ...

What is the best way to transform this date string into a valid Firestore timestamp?

Currently, I am facing an issue in my Angular application that is integrated with Firebase Firestore database. The problem lies in updating a date field from a Firestore timestamp field. To provide some context, I have set up an update form which triggers ...