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

Vue 3 gracefully handles errors by displaying an alternative component

I am currently developing a rendering library for my Vue 3 + Vite project. Essentially, I have a JSON array of products which I pass to a special <Render :products /> component. This Render component reads all the JSON products and converts them in ...

Stop the click event using a confirmation dialog before proceeding with the operation

I'm trying to implement a confirmation dialog before deletion by using e.preventDefault() to prevent immediate deletion. However, I am facing an issue in the YES function where I would like to resume the click event's operation with return true w ...

What is causing this form to submit?

I need help with sending emails via AJAX. My problem is that the form keeps submitting and refreshing, even though I haven't used GET to send anything in the URL. HTML: <form onsubmit="ajaxEmail(); return false;" > <input type=" ...

The SetInterval function will continue to run within a web component even after the corresponding element has been removed from the

I am currently engaged in developing a straightforward application that coordinates multiple web components. Among these components, there is one that contains a setInterval function. Interestingly, the function continues to run even after the component it ...

Problem with locating elements using Selenium xpath

While using selenium and xpath, I encountered a peculiar issue. On a page, there are 25 <a> tags with nested <img/> tags. I am trying to retrieve all these elements using the findElements() method. Interestingly, upon inspecting the page source ...

React failed to render the information fetched from an API following a GET request made in componentDidMount()

I recently implemented a function in my React code that calls an API and updates the state based on the data it receives. getUserList() { API.get('/userlist') .then(response => { this.setState({ userLis ...

In React, firebase.firestore() is operational, but firebase.functions() remains undefined

Currently, I am engaged in a React project that heavily relies on Firebase for various features. In order to incorporate HTTPS callable functions into the project, I encountered an issue. The problem lies in the incorrect importation of the 'firebase ...

Preventing Div items from rearranging during size transitions using toggleClass

When I click on an element with the ID "id", I use toggleClass to resize a div from 10px to 500px in width. This is done partly to show/hide content. However, the issue arises when the transition occurs and the contents of the div start rearranging, overfl ...

When an Ajax post request is made, the data being sent is appended to the JSON response

Having a dilemma with my ajax call: $.ajax({ url: '/assets/functions.php', type: 'POST', data: { "functionCall": "get-uploads", "type": type }, dataType: 'json', success: function (data ...

Angular app - static List mysteriously clears out upon refresh

My goal is to create a login page using Angular. I have an Angular component with HTML, CSS, and TypeScript files that manage this functionality. The HTML file contains two fields (Username and Password) and two buttons (Login and Register). When a user en ...

Guide to creating content on an NFC tag with Ionic

I am struggling with my button calling the test2 function and the code I have is not working as expected. Here is what I currently have: import { Component } from '@angular/core'; import { NFC, Ndef } from '@ionic-native/nfc/ngx'; @Com ...

Queueing up file downloads through a web browser

When trying to download multiple files from a server, I am required to queue them up instead of downloading in parallel. Unfortunately, I do not have access to the download server, so my only option is to work with the browser. Is there an API available t ...

Selecting the next element in the DOM using Javascript

Here is the structure of my current setup: <div class="wrapper"> <div class="first"> <a class="button" href="">click</a> </div> <div class="second"> <div class="third"> S ...

Jest encountered an error while attempting to parse the TypeScript configuration file

I've been working on setting up Jest with Babel and Typescript, following the guidelines provided here. However, when I run npm run test, I encounter the error message: Error: Jest: Failed to parse the TypeScript config file C:...jest.config.js` Th ...

Exploring Material UI: Understanding the contrast in functionalities between incorporating the Icon component and the Material Icons node

I am looking to incorporate Material Icons into my application. I have come across two methods provided by Material UI for adding the same icon to my site: Using the <Icon /> component, which is part of the @material-ui/core package: <!-- Add t ...

The JQuery mobile navigation menu effortlessly appears on your screen

I am experiencing an issue with a JQuery mobile navigation that is designed for screens @979 pixels wide. The problem arises when the screen is resized to 979px - the menu pops up fully extended and covers the content of the web page. I suspect that this ...

Looking to streamline your webpack configuration in vue.config.js? Utilize webpack-chain for efficient setup. And, wondering how to leverage the speed-measure-webpack

Below is the setup in my vue-cli3 configuration file: vue.config.js: const path = require('path') const CompressionWebpackPlugin = require('compression-webpack-plugin') const SpeedMeasurePlugin = require("speed-measure-webpack-plugin" ...

Accessing the element within an ion-tab using document.getElementById

Within my ion-view, I have ion-tabs containing a canvas element. However, when attempting to retrieve the canvas using document.getElementById('photoCanvas'); I receive 'undefined'. Here is the code snippet: HTML: <ion-view ...

Cloned element does not trigger on click event

When using jQuery 1.10, I encountered an issue where cloning a div containing a button with a click event defined did not retain the click event on the cloned div. I have come across similar questions multiple times, and existing solutions advise using cl ...

Fixing Error 415 when Sending Angular Posts to Asp.Net Web Api on IIS

I'm having a difficult time figuring out how to make a simple Web Api call work, and I'm feeling quite frustrated because it's much more complicated than anticipated. I have created a basic Web Api (for testing purposes) that is being consu ...