Updating a property in a JavaScript object using Angular

Working with Angular, I have a dataset:

export class AppComponent {

data = [ 
    {
      "area1": {
        "format": "changethis"
    }
]

I am looking to develop a function that can alter the value of a specific key. For example:

  changeKeyValue() {
    const key = data[0].area1.format;
    const value = 'someOtherValue';
    // Implementation needed to update the value
  }

}

Any suggestions on how I could achieve this task?

Answer №1

To update a specific element within an array, you can target the index data[0] or data[index] and make the necessary changes.

data = [ 
    {
      "area1": {
        "format": "changethis"
      }
    }
]

let value = "New value"  
data[0].area1.format = value;

or

data[0].area1["format"] = value;

If you wish to update all instances of the "format" attribute in your array, you can utilize any array method and iterate through each item to update their values accordingly.

For example:

data.forEach(item=>item.area1.format = 'new text')

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

Displaying a limited number of dynamically generated values in an Angular select dropdown using Bootstrap 5

I have a backend service that provides a list of all countries. In my component, I iterate through the array and allow the user to select a country. Bootstrap 5 is being used for styling. <select class="form-select" formControlName="coun ...

Using Angular Material to link a constant within an HTML file

I have set up my constants in the following way: constants.ts export const Constants = Object.freeze({ ACCEPTED_LEADS_TO_CALL: "Accepted Leads to Call", RECOMMENDED_CALL_LIST: "Recommended Call List" }); This makes it easy to refere ...

Using 'cy.get' to locate elements in Cypress tutorial

Is there a way to search for one element, and if it's not found, search for another element? cy.get(@firstElement).or(@secondElement).click() Can I use a function similar to || in conditions for this scenario? ...

Activating functions based on radio button selection in React with TypeScript

Below are the radio buttons with their respective functions: <div className="row"> <div className="col-md-4"> <label className="radio"> <input onChange={() => {serviceCalc()}} ty ...

Show values in an angular template using an array

I want to showcase values of an array using *ngFor const blockData = [ {text: sampleText1, array: [val1]}, {text: sampleText2, array: [val2, dat2]}, {text: sampleText3, array: [val3, dat3]} ] <div *ngFor="let data of blockData"> ...

Should one bother utilizing Promise.all within the context of a TypeORM transaction?

Using TypeORM to perform two operations in a single transaction with no specified order. Will utilizing Promise.all result in faster processing, or do the commands wait internally regardless? Is there any discernible difference in efficiency between the t ...

Is it normal for TypeScript to not throw an error when different data types are used for function parameters?

function add(a:number, b:number):number { return a+b; } let mynumber:any = "50"; let result:number = add(mynumber, 5); console.log(result); Why does the console print "505" without throwing an error in the "add" function? If I had declared mynumber ...

Using Typescript with d3 Library in Power BI

Creating d3.axis() or any other d3 object in typescript for a Power BI custom visual and ensuring it displays on the screen - how can this be achieved? ...

Error Loading Chunks in Angular ThreeJS Application Specifically in Safari

I've been working with ThreeJS in Angular. After compiling and uploading the latest version of my app to the server last week, I encountered the following errors on Mac and iPhone: SyntaxError: Left hand side of operator '=' must be a refere ...

When utilizing the @Prop decorator in TypeScript, the compiler throws an error prompting the need to initialize the prop

Currently, I am utilizing Vue in combination with TypeScript along with the 'vue-property-decorator' package. When attempting to utilize a prop as shown below: @Prop({ default: '' }) private type: string An error is triggered by the ...

Create an array using modern ES6 imports syntax

I am currently in the process of transitioning Node javascript code to typescript, necessitating a shift from using require() to import. Below is the initial javascript: const stuff = [ require("./elsewhere/part1"), require("./elsew ...

The malfunctioning collapse feature in Bootstrap 4 sidebar within an Angular 6 application

I am trying to find a way to collapse and reopen the sidebar when clicking on a button. I have attempted to create a function to achieve this, but unfortunately it did not work as expected. Important: I need to collapse the sidebar without relying on jque ...

The latest version of npm packages is not displayed when you hover over them in Visual Studio Code

Previously in package.json, I was able to check the latest versions of packages by hovering over each package version as a "tooltip", but that feature seems to have disappeared now. I am using VSC version 1.19.2. I am navigating through a proxy. I ha ...

Error in InversifyJs exclusively occurring in Internet Explorer

I'm currently utilizing Typescript with webpack for the development of a web application. Recently, I made the transition to using the inversifyJs DI library. However, I am encountering a specific error only when testing on Internet Explorer (version ...

Utilizing @ngrx/router-store in a feature module: A comprehensive guide

The NGRX documentation for Router-Store only showcases an example with .forRoot(). Upon experimenting with .forFeature(), I realized that this static method does not exist. I am interested in defining certain actions and effects to be utilized within my f ...

Incorporating an expansion panel within an Angular Material table row

I'm currently working on incorporating an expansion panel, possibly a new component, similar to the mat-accordion. This will allow for a detailed view to be displayed within a mat-table row upon clicking. To better illustrate this requirement, I have ...

What is the most effective way to utilize getStaticPaths in a dynamic manner within next.js

There is a need to paginate static pages for each of the 3 blog categories, but the problem lies in the variable number of pages and the inability to access which category needs to be fetched in getStaticPaths. The project folder structure appears as foll ...

Looking to showcase a .tif image in your Angular project?

This code is functioning properly for .png images. getNextImage(imageObj:{imageName:string,cityImageId:number,imgNumber:number}):void{ this.imgNumber= imageObj.imgNumber; this.imagePath=`assets/images/${imageObj.imageName}.png`; this.cityIma ...

Discovering the proper method for indicating the type of a variable in the middle of a statement

In my code, there was a line that looked like this: let initialPayload = this.db.list("/members").snapshotChanges() as Observable<any[]> But then I changed it to this: let initialPayload = this.db.list("/members").snapshotChanges ...

Setting Values in Angular Reactive Forms Programmatically

I am working on an Angular Reactive Form that includes validation. I need assistance with properly calling the setter for my hiddenComposedField. app.component.ts ngOnInit() { this.myForm = this.formBuilder.group({ 'field1': ['' ...