Navigating an immutable list to make updates to its values

Within this list, I have an unalterable group of objects. My task is to change the value of the 'isReq' property to false for all objects except the one with the id 2.

[
{
    'id': 1,
    'name': 'Ram',
    'Details': {
        'isReq': true
    }
},
{
    'id': 2,
    'name': 'dev',
    'Details': {
        'isReq': true
    }
},
{
    'id': 3,
    'name': 'joe',
    'Details': {
        'isReq': true
    }
}

]

Answer №1

Implement map function with an if-else statement:

list.map(item => {
  if (item.id === 5) {
    return item
  } else {
    return { ...item, Details : {isRequired': true} }
  }
}

In this example, we are using the object spread operator to modify the item, but you also have the option to use Object.assign or any other method.

Answer №2

I found a resolution to the issue I was facing right here, although I'm not certain if it's the most efficient approach.

const selectedId = 2;
        const arr = fromJS(
            [{ 'id': 1, 'name': 'Ram', 'Details': { 'isReq': true } },
            { 'id': 2, 'name': 'dev', 'Details': { 'isReq': true } },
            { 'id': 3, 'name': 'joe', 'Details': { 'isReq': true } }]);

        const newarr = arr.map(function (val: any, index: any) {
            if (val.get('id') === selectedId) {
                return val.setIn(['Details', 'isReq'], true);
            } else {
                return val.setIn(['Details', 'isReq'], 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 apply a single pipe to filter columns in Angular 2 with an array of values

I need to sort through an array of objects using multiple array string values. Here is an example of how my array of objects looks like: [{ "name": "FULLY MAINTAINED MARUTI SUZUKI SWIFT VDI 2008", "model": "Swift" }, { "name": "maruti suzuki ...

"Utilizing FormData in an IONIC 5 project with

While creating a user profile, I am encountering an issue where the FormData being generated for sending is empty despite all other fields having values. Below is the code snippet from cadastro.ts: import { Component, OnInit } from '@angular/core&ap ...

What could be preventing my state from changing to false when I click the close button on the menu?

Despite initializing my state to false, the problem arises when I open and close my menu. The state never actually becomes false, causing the closing animation of the NavBar to not run as expected. The component: import CloseButton from "./CloseButto ...

Extract a string value from a TypeScript enum

Here is a basic enum definition: export enum Type { TEST_ONE = "testing.one", TEST_TWO = "testing.two", BETA = "beta.one" } I am looking to run a function for each string value in the enum. For example: executeType(type: string) { console.lo ...

When considering Angular directives, which is more suitable for this scenario: structural or attribute?

In the process of developing an Angular 5 directive, I aim to incorporate various host views (generated from a component) into the viewContainer. However, I find myself at a crossroads as to whether I should opt for an attribute directive or a structural ...

Navigating through code in a monorepo using VSCode, Lerna, and Typescript

We maintain all of our Javascript related SDKs in a monorepo at Sentry. https://github.com/getsentry/sentry-javascript If you decide to clone this repository, make sure to properly set it up by running yarn install and then navigate to any file such as p ...

Separate an array in TypeScript based on the sign of each number, and then replace the empty spaces with null objects

Hey, I'm facing a little issue, I have an Array of objects and my goal is to split them based on the sign of numbers. The objects should then be dynamically stored in different Arrays while retaining their index and getting padded with zeros at the b ...

Using Typescript to Define Mongoose Schemas

Currently exploring the creation of a user schema in TypeScript. I've observed that many people use an interface which functions well until I introduce a message involving username.unique or required property. No error code present: import {model, mo ...

What could be causing my D3.js stacked bar chart to show inaccurate results?

I'm encountering some challenges while creating a stacked bar chart in d3.js. The current appearance of my chart is depicted here (developed with D3.js): https://i.sstatic.net/G6UA6.png However, I aim to achieve a design similar to this one (crafted ...

What could be the reason behind Typescript's unexpected behavior when handling the severity prop in Material UI Alerts?

Trying to integrate Typescript into my react project and encountering a particular error: Type 'string' is not assignable to type 'Color | undefined'. The issue arises when I have the following setup... const foo = {stuff:"succes ...

The Observable constructor in Nativescript must be called with the 'new' keyword in order to be invoked

I am facing a challenge while attempting to upload a multipart form in nativescript using http-background. The error message "Class constructor Observable cannot be invoked without 'new'" keeps appearing. I have tried changing the compilerOptions ...

Issue with Adding Additional Property to react-leaflet Marker Component in TypeScript

I'm attempting to include an extra property count in the Marker component provided by react-leaflet. Unfortunately, we're encountering an error. Type '{ children: Element; position: [number, number]; key: number; count: number; }' is n ...

When defining a class property in TypeScript, you can make it optional by not providing

Is there a way to make a property on a Class optional without it being undefined? In the following example, note that the Class constructor takes a type of itself (this is intentional) class Test { foo: number; bar: string; baz?: string; construc ...

Issue with Angular Provider Missing in Ahead-Of-Time Compilation

My goal is to simplify the declaration of a provider by using a static function in this way: const provider = MyModule.configureProvider(); @NgModule({ bootstrap: [AppComponent], declarations: [AppComponent], imports: [ ... ], providers: [ ...

Pass on only the necessary attributes to the component

I have a simple component that I want to include most, if not all, of the default HTML element props. My idea was to possibly extend React.HTMLAttributes<HTMLElement> and then spread them in the component's attributes. However, the props' ...

Utilizing React TypeScript within Visual Studio

Utilizing the most recent editions of Visual Studio and Visual Studio Code, I have initiated a project using create-react-app with TypeScript react scripts version. My objective is to host my project within a .NET Core web application that I've estab ...

A unique column in the Foundry system that utilizes function-backed technology to calculate the monthly usage of engines over a

In my dataset of ‘Engine Hours’, I have the following information: Engine# Date Recorded Hours ABC123 Jan 21, 2024 9,171 ABC123 Dec 13, 2023 9,009 ABC123 Oct 6, 2023 8,936 XYZ456 Jan 8, 2024 5,543 XYZ456 Nov 1, 2023 4,998 XYZ456 Oct 1 ...

Creating tests in JestJs for React components that utilize Context Provider and Hooks

As a newcomer to front-end development, I am currently working on authentication with Okta-React. To pass logged-in user information across multiple components, I'm utilizing React context with hooks. While this approach works well, I encountered an i ...

update the value of a specific document in Firestore by specifying its

Is there a way to update document values in a Firestore collection for multiple records without manually specifying each document ID? Currently, I have a method that works for updating individual documents using their IDs, but what if I need to update a la ...

Using React and Typescript: Populating an array within a For Loop using setTimeout is not happening sequentially or at all

I'm currently working on a function that animates images of random cars moving across the screen. My goal is to stagger the population of the "carsLeft" array using setTimeout, where I will eventually randomize the delay time for each car. Everything ...