Updating the value of a key in an object is not functioning as expected

There is a single object defined as

requestObject: any = {
    "type": 'type1',
    "start": 0,
    "size": 10,
    "keywords": ['abcd','efgh'],
    filters: [],
  }

Next, attempting to change the value for keyword, I updated it like so:

 requestObject['keywords'] =  ['pqr']

Despite this change, the console log still displays the initial value.

"keywords": ['abcd','efgh'],

I then attempted to delete the key and add the modified value with the same key name, yet the result remained unchanged.

delete requestObject.keywords
requestObject['keywords'] =  ['pqr'];

Explanation in Detail:

There are two sibling components, referred to as A and B (NgbModal). Within component A, there exists a request object. When a button within component A is clicked, component B (NgbModal) appears allowing for value updates which can then be submitted. Upon submission, the values are sent back to Component A using an event emitter and captured using:

modalRef.componentInstance.filterApplied.subscribe((res: any) => {}

Ultimately, when attempting to update the object in Component A, the changes do not reflect and the old values persist.

Answer №1

It seems like you might be encountering the concept of "immutability".

It appears that your response object is being returned through HttpResponse, which, as per the documentation, has a read-only body.

Even if this isn't the primary issue in this case, it's generally recommended to refrain from directly altering an object like a server response. A more advisable approach would be to create a new object and make modifications there.

You could try implementing one or both of these solutions:

const requestObject: any = {
  "type": 'type1',
  "start": 0,
  "size": 10,
  "keywords": ['abcd','efgh'],
  filters: [],
}


// -----------
// solution 1:
// Create a new object by spreading the old one and updating the 'keywords' property

const updatedRequest = {...requestObject, keywords: ['pqr'] }
console.log(updatedRequest)


// -----------
// solution 2:
// Perform a deep copy using JSON.stringify + JSON.parse

const clonedRequest = JSON.parse(JSON.stringify(requestObject))
clonedRequest.keywords = ['pqr']
console.log(clonedRequest)

Answer №2

After running the code in my console,

{
    "type": 'type1',
    "start": 0,
    "size": 10,
    "keywords": ['abcd','efgh'],
    filters: [],
}

I noticed that any was assigned with the code block, instead of requestObject. This is because when using any =, it assigns everything after the equal sign to any without returning anything. Additionally, assigning values using a colon outside of object definitions may not work as intended. I encountered an issue where resultObject was undefined for me. To fix this, consider replacing your assignment statement with:

requestObject = {
    "type": 'type1',
    "start": 0,
    "size": 10,
    "keywords": ['abcd','efgh'],
    filters: [],
}

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

Turn off hover effect for the v-checkbox component in Vuetify 2

Is there a way to prevent the darkened circle from appearing behind a v-checkbox in Vuetify 2 when hovering over it? My v-checkbox is currently enclosed within a v-tab and a v-tooltip, although I'm not sure if that has any impact. <v-tab v-for=&quo ...

Exploring the implementation of binding a dynamic title using interpolation within a Kendo TabStrip component in an Angular 2

I have been attempting to bind interpolated titles into a Kendo TabStrip for Angular 2, but my code doesn't seem to be functioning correctly. When using hardcoded data without interpolation, everything works fine. However, when trying to incorporate ...

Stop materializecss dropdown from closing when clicking within it

As I work on my current project, I am utilizing Materialize.css which includes a dropdown with various input forms inside. The dropdown can be closed by: clicking outside of .dropdown-content clicking inside of .dropdown-content clicking on .dropdown-bu ...

Adjusting the amount of rows and columns in a fluid manner with CSS grid (updated)

After conducting my research, it seems that the most effective way to set the final value of a CSS grid is either by directly specifying it or by creating/manipulating the css :root value. A similar query was previously raised here, although the answers p ...

Utilize ES6 syntax to bring in a package as an extension of another package

To expand map projections in D3, it is recommended to import the necessary packages like so: const d3 = require("d3") require("d3-geo-projection")(d3) This allows you to access methods such as d3-geo-projection's geoAiry method fr ...

I am puzzled by the issue with my logic - the button only changes once and then the onclick function ceases to work

I am having an issue with a button that should switch between displaying temperatures in Fahrenheit and Celsius when clicked. It works for the first two clicks, but on the third click, it stops working even though I've set the class back to .temp. $( ...

Trigger the original function again once the other function completes in jQuery AJAX

I'm working on improving my skills in jQuery, AJAX, and JSON. Within my application, there is a dropdown select menu: <select id="serviceload" name="serviceload"></select> The OPTIONS in the select menu are populated dynamically by anot ...

Ways to pass JavaScript variables to a Python script

Hey there! I'm currently facing an issue with retrieving variables from JS to use in my python code. Despite trying methods like AJAX and JQuery, I haven't had much success yet. It's possible that I'm missing something crucial in the pr ...

How can I detect a change in user input using jQuery?

When utilizing jquery .oninput with an element, the event will trigger instantly whenever there is a change in the input value. In my scenario, it is necessary for me to validate the input value by calling the service immediately after any changes occur. ...

Choosing between creating a class with a shared instance or not

I'm curious if my class is shared across instances: for example, I have a route that looks like this: /student/:id When this route triggers the controller (simplified version): module.exports = RecalculateStudents; const recalculateActiveStudent ...

TS2786 TypeScript is failing to recognize the UI-Kitten components

Error message on IDE: Error Encountered: 'ApplicationProvider' cannot be used as a JSX component. The instance type 'ApplicationProvider' is not a valid JSX element. The types returned by 'render()' are incompatible betwe ...

The CSS class is specifically assigned to a single element

After every two seconds, my JavaScript function is triggered and based on certain logic, I aim to add a CSS class with an effect to an HTML element on the page. var counter = 0; $interval(function () { counter++; ...

The value of a variable remains constant in an Angular controller

I am facing an issue with my HTML page that includes: <div ng-controller="MyCtrl"> <div ng-view>Some content</div> myVar: {{myVar}} </div> Along with an Angular controller: myModule.controller('MyCtrl', function($s ...

Firestore experiencing difficulty fetching / showing data

For some reason, Firestore is unable to retrieve or display data from a Collection named data. This issue emerged after I attempted to simplify my code. Take a look at the code snippet: Filename: database.component.ts import { Component, OnInit } from & ...

Looking for a unique search object specifically designed for mongodb?

I am currently developing my first application using node.js and angular, and I have encountered a challenge that I am struggling to solve. Let's say I have a User Schema like this: User = { firstname: "Bryan", lastname: "Allan", email: "<a ...

Is it possible to update table cell content depending on selected option?

Displayed here is the select block: <form> <select id="select"> <option disabled selected value="choose"> CHOOSE </option> <option value="i2g" id="i ...

Using Jquery to detect if there are any Space characters in the user input

In my form, users are required to set up a new Username. The problem arises when they include a space in their username, which I want to prevent. Currently, I am able to detect the presence of a space with this code: var hasSpace = $('#usernameValue ...

Why include HTML in our webpack bundle?

Hello there, I am currently working on an angular 2 app using this starter pack as a base. I am trying to understand what our build process will entail. I have noticed that when running: npm run build:prod npm run server:prod The HTML content is incl ...

Display information upon the clicking of a button and update the color of the selected button

When a button is pressed, I want to display content and change the color of the active button. Currently, I can do each operation individually, but I'm struggling to merge these functionalities. This is how my script looks like for displaying the con ...

Update the numerical data within a td element using jQuery

Is there a way to use jquery to increase numerical values in a <td> element? I've attempted the following method without success. My goal is to update the value of the td cell by clicking a button with the ID "#increaseNum". Here is the HTML st ...