Modify a particular attribute in an array of objects

I am currently working on an Angular project and dealing with the following array object:

{
    "DATA": [
        {
            "CUSTOM1": [
                {
                    "value": "Item1",
                    "isSelected": true
                },
                {
                    "value": "Item2",
                    "isSelected": true
                },
                {
                    "value": "Item2",
                    "isSelected": false
                },
                {
                    "value": "Item3",
                    "isSelected": false
                }
         
            ],
         CUSTOM2": [
                {
                    "value": "Item11",
                    "isSelected": true
                },
                {
                    "value": "Item12",
                    "isSelected": true
                },
                {
                    "value": "Item13",
                    "isSelected": false
                },
                {
                    "value": "Item14",
                    "isSelected": false
                }
         
            ]
        }
    ]
}

I need to update the isSelected value to false in the CUSTOM1 object. How can I accomplish this in TypeScript?

Your insights and solutions would be greatly appreciated. Thank you!

Answer №1

execute the code below:

let data = {
    "DATA": [
        {
            "CUSTOM1": [
                {
                    "value": "Item1",
                    "isSelected": true
                },
                {
                    "value": "Item2",
                    "isSelected": true
                },
                {
                    "value": "Item2",
                    "isSelected": false
                },
                {
                    "value": "Item3",
                    "isSelected": false
                }
         
            ],
         "CUSTOM2": [
                {
                    "value": "Item11",
                    "isSelected": true
                },
                {
                    "value": "Item12",
                    "isSelected": true
                },
                {
                    "value": "Item13",
                    "isSelected": false
                },
                {
                    "value": "Item14",
                    "isSelected": false
                }
         
            ]
        }
    ]
};
data.DATA[0].CUSTOM1.forEach((val) => val.isSelected = false);

Answer №2

Your input resembles a JSON format and must be converted to a JavaScript object before processing.

Once the conversion is done, navigate through the DATA array to access each CUSTOM1 element. Change the value of the isSelected property to false.


// Simplified version of the provided example
const jsonString = `{"DATA": [{ "CUSTOM1": [{ "value": "Item1", "isSelected": true}]}]}`

const parsedJson = JSON.parse(jsonString);

const data = parsedJson.DATA;

data.forEach(d => 
  d.CUSTOM1.forEach(c1 => c1.isSelected = false)
);


Typically, these strings are received from backend APIs with a known structure. It's advisable to define a type or interface to represent it. Using TypeScript offers the advantage of utilizing the type system effectively.


type CUSTOM1 = {
    value: string;
    isSelected: boolean;
};

type CUSTOM2 = {
    value: string;
    isSelected: boolean;
};

type DATA = {
    custom1: CUSTOM1[];
    custom2: CUSTOM2[];
};

const data: DATA[] = [
    {
        custom1: [
            { value: 'item1', isSelected: true }
        ],
        custom2: [
            { value: 'item11', isSelected: false }
        ]
    }
];

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

How to retrieve a Typescript variable within an ngIf conditional statement in Angular

How can I access a TypeScript variable inside an ngIf statement? TS: public data: string; HTML: <td> <div *ngIf="data === 'BALL' ; else noplay" >{{ play }}</div> <ng-template #noplay> {{ gotohome ...

Transforming various date formats into the en-US format of mm/dd/yyyy hh:mm:ss can be accomplished through JavaScript

When encountering a date format in en-GB or European style (mm.dd.yyyy), it should be converted to the en-US format (mm/dd/yyyy). If the date is not already in en-US format, then it needs to be converted accordingly. ...

How can we eliminate the modal-open class in Angular when transitioning to a different URL?

Currently, I am facing an issue with a bootstrap modal. There is a button inside the modal which upon clicking should navigate the current component to another component named 'questions'. The problem arises when the new component is loaded, as t ...

What are some techniques to encourage a grandchild to utilize the grandparent <router-outlet> within Angular 6?

This link will take you to a Stack Blitz demo that illustrates what I'm trying to achieve: https://angular-czk5vj.stackblitz.io/ In essence, my goal is to have the grand child route render within the grand parent router-outlet. Example: Routes: Emp ...

There seems to be an issue with the 'clr-icon' element; it is not recognized as a valid element

When I run this specific command: ng build --prod --base-href ./ An error message is displayed: ERROR in : 'clr-icon' is not a known element: 1. If 'clr-icon' is an Angular component, then verify that it is part of this module. 2. If ...

Is there cause for worry regarding the efficiency issues of utilizing Object.setPrototypeOf for subclassing Error?

My curiosity is piqued by the Object.setPrototypeOf(this, new.target.prototype) function and the cautionary note from MDN: Warning: Modifying an object's [[Prototype]] is currently a slow operation in all browsers due to how modern JavaScript engines ...

Filtering data in an antd table by searching

Just starting out with React hooks, specifically using TypeScript, and I'm struggling to implement a search filter with two parameters. Currently, the search filter is only working with one parameter which is 'receiver?.name?'. However, I wo ...

Guide to resolving a Promise that returns an array in TypeScript

My goal is to retrieve an array in the form of a promise. Initially, I unzipped a file and then parsed it using csv-parse. All the resulting objects are stored in an array which is later returned. Initially, when I tried returning without using a promise, ...

What is the proper way to structure a React component class without any props?

When working with Typescript in a React project, the top level component typically does not receive any props. What is the recommended approach for typing this scenario? I have been using the following coding structure as a template, but I am curious if t ...

Ways to ensure the React prop type matches the value provided when using typescript?

Within my List component, there are 2 props that it takes in: items = an array of items component = a react component The main function of the List component is to iterate over the items and display each item using the specified component. // List ...

index signature in TypeScript is an optional feature

Is it possible to create a type with optional namespaces in TypeScript? export interface NodesState { attr1: number; attr2: number; attr3: number; } The goal is to allow users to namespace the type like this: { namespace1: { attr1: 100, ...

Tips for defining the type of any children property in Typescript

Currently, I am delving into Typescript in conjunction with React where I have a Team Page and a slider component. The slider component is functioning smoothly; however, my goal is to specify the type of children for it. The TeamPage import react, { Fragm ...

Typescript error when using fill or justify prop in React-bootstrap with Typescript

Code import { useCallback, useState, useEffect } from 'react'; import { Tabs, Tab, Spinner, Alert } from 'react-bootstrap'; import { Categories } from '../../models/ICategory'; import IMovie from '../../models/IMovie&apo ...

Issues with loading SourceMap in DevTools after upgrading from Bootstrap 3 to 4

I am currently working on a project with Angular 6 and .NET MVC where I am in the process of upgrading from Bootstrap 3 to Bootstrap 4. Initially, I had been using the Bootstrap 3 CDN and everything was working smoothly. However, I recently had to switch t ...

What is the best way to include an object in a document before sending it back?

I am facing a challenge that involves retrieving data from Firestore using angularfire. Once I fetch a collection, I need to iterate through each document in the collection and then make a separate request to Firestore to get additional document values. Th ...

Incorporating .npmrc configuration into an Angular application

It seems like I'm missing a crucial step in this process. I went ahead and added an .npmrc file to the root of my angular project, inserting the following line: @example/xxx:registry=ssh/url/of/my/private/repo/in/bitbucket Subsequently, I included @e ...

Steps for activating Brotli compression in Nginx and Docker for an Angular Application

For my Angular application using Docker, I have implemented Brotli compression on Nginx by adding commands to the Dockerfile and enabling brotli in the nginx/default.conf file. nginx/default.conf: server { brotli on; brotli_static on; listen ...

Issue: The AppModule is missing NgModule metadata when running on a different machine

I am facing an issue while trying to deploy my Angular project on AWS S3. The problem arises when I attempt to run the 'ng build' command, but interestingly, everything works fine on my local machine. Even though all dependencies are identical, ...

Using NgControl with a Custom Directive in Angular 2

Using ngControl on a custom component has been a challenge for me. I successfully created the component and implemented ControlValueAccessor but encountered issues with updating form classes (ng-pristine, ng-touched, ng-invalid) and checking the value of t ...

Retrieving the attribute key from a dynamically typed object

Having this specific interface structure: interface test { [key: string]: string } along with an object defined as follows: const obj: test ={ name: 'mda', telephone: '1234' } Attempting to utilize this object in a variab ...