What is the best way to update a deeply nested array of objects?

I have an array of objects with nested data that includes product, task, instrument details, and assets. I am attempting to locate a specific instrument by supplier ID and modify its asset values based on a given number.

const data = [
  {
    // Data for the first product...
  },
  {
    // Data for the second product...
  }
];

The goal is to update the assets of the selected instrument in each product entry by multiplying all asset values by a specified number. However, my current function is throwing an error:

Uncaught TypeError: Cannot assign to read only property 'current' of object '#'

How can I resolve this issue and successfully update the data as intended?

Answer №1

It is essential to ensure that the map function returns a new object of type instrumentDetail instead of modifying the existing object.

(instrumentDetail: any) => {
  const assets = instrumentDetail.instrument.supplier.id === supplierInstrumentId
    ? Object.fromEntries(
      Object.entries(instrumentDetail.assets).map(([k, v]) => [k, v + 5])
    )
    :
    instrumentDetail.assets;
    
  return {
    ...instrumentDetail,
    assets
  };
}

Answer №2

The issue with your product map not returning is causing the undefined error to occur. Interestingly, I did not encounter the TypeScript error you mentioned earlier. This adjustment should maintain the array in the desired state.

function updateProductArray(productsArr, supplierInstrumentId) {
  return productsArr.map((product) => {
    product.instrumentDetails.map((instrumentDetail) => {
      if (instrumentDetail.instrument.supplier.id === supplierInstrumentId) {
        instrumentDetail.assets.current += 5;
        instrumentDetail.assets.fixed = instrumentDetail.assets.fixed + 5;
        instrumentDetail.assets.financial = instrumentDetail.assets.financial + 5;
        instrumentDetail.assets.cash = instrumentDetail.assets.cash + 5;
        return instrumentDetail;
      }
    });
    return product;
  });
}

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

What is the best way to play a video from a certain time point in a React application?

How can I make my component automatically play from a specific time like 00:07:12,600 instead of starting from the beginning? import style from './Hero.module.css'; import Image from 'next/image'; import ReactPlayer from 'react-pla ...

Is there a way to determine if a specific string matches a value within an object?

Within my codebase, there exists an object named "codes": var codes = { code1: 'test1' code2: 'test2' } I am looking to determine if this object possesses a specific property and then display the result in the console. if(inp ...

I implemented progress bars in Angular 2 that have changing maximum values. The service updates the maximum value for each bar dynamically. Currently, the progress bars are functioning at 100% capacity

this.games=[ {"val":50, "name":"Articlescontributed","max":35}, {"val":30 ,"name":"Articlesrated", "max":999}, {"val":20, "name":"Views", "max":35}, {"val":30, "name":"Ratings", "max":35}, {"val":20, "name":"Follower", "max":200}, { ...

What is the best way to generate a multi-dimensional array filled with random integers and display it using a custom function?

Greetings fellow programmers! I could use some assistance with an assignment that has me scratching my head. Despite my best efforts, my professor hasn't been much help, and I've scoured both textbooks and YouTube without success. The task at han ...

Guide on creating a readUInt16BE function in a Node.js environment

Looking to implement the readUint16BE function in node.js, here's how it is declared: buf.readUInt16BE(offset, [noAssert]) Documentation: http://nodejs.org/api/buffer.html#buffer_buf_readuint16be_offset_noassert This function reads an unsigned 1 ...

Is it possible to consolidate React and React-DOM into a unified library instead of having them separate?

Is it possible to combine React.JS and React-DOM.JS into a single library? In all the web applications I've encountered, we always have to import both libraries separately. Have there been any cases where either of these libraries can be used on its ...

Error in React Native Typescript: The type 'string' cannot be assigned to the type '"solid" | "clear" | "outline"'. (Error code: ts(2322))

I have integrated TypeScript with React Native in my project. import React from 'react'; import { Button } from 'react-native-elements'; import { IThemedButton } from '../../../models/themedButton'; interface IThemedButtonPr ...

Unable to modify translation values in an existing ngx-translate object

I am facing an issue where I am unable to change the value of an object property within a translation JSON file using ngx translate. Despite attempting to update the value dynamically when receiving data from an API, it seems to remain unchanged. I have t ...

When the child of li is clicked instead

Below is a list I have: <ul id="orderlist"> <li id="2"> <span class="pull-right value">Ready</span> <img src="" class="img-responsive"> Filet Mignon <small>2 servings</small> <small ...

Collaborating and monitoring data between controllers

A unique challenge has arisen as we implement a tree-style navigation element that must communicate with other directives/controllers. The main objectives are: Keep track of the current selection, Detect when the row selection changes. The task at hand ...

Can auto-import be configured in WebStorm without using double dots?

Is it feasible to configure WebStorm for automatic import of modules/Component/components/MyComponent instead of using ../MyComponent? ...

Is it possible to invoke a component's function within the click function of a Chartjs chart?

How do I trigger a function in my Component from an onclick event in my chart.js? export class ReportesComponent implements OnInit { constructor(public _router: Router, private data: ReporteService) {} this.chart = new Chart('myChart', { ...

What is the process for using dojo to load content?

As I work on creating a single-page website with the help of dojo, I refer to tutorials that explain how to utilize dojo/request for ajax requests. The process is straightforward - simply make a request, receive HTML content, and insert it into a designate ...

Having trouble understanding why the other parts of my header are not displaying

<head> This special function runs when the webpage is loaded. <body onload="myOnload()"> A distinctive div at the top with a unique graphic <div id="header"> <img src="resumeheader.png" alt="Header" style="width:750px;h ...

Margins are added to cards on the right side

Looking for some help to improve the display of three cards in a grid. The card media has a max-width of 345px, but this is causing excessive margin-right space and making the styling look poorly. Any suggestions on how to eliminate this extra margin? If ...

Ajax alert: The index 'id' is not defined

I'm currently learning PHP and scripting, but I am encountering some difficulties when it comes to sending information to PHP. I would appreciate any help you can offer. Thank you for your assistance. Here is the issue at hand: Error Message: Noti ...

Prevent data loss on webpage refresh by using Angular's local storage feature

As a beginner in Angular, I am exploring ways to retain user input and interactions on my webpage even after a refresh. After some research, I came across using local storage as a viable solution. A different answer suggested utilizing the following code s ...

Optimal DynamoDB Configuration for Effective Implementation

Currently, I am developing a save application where users can save articles to their profile. Instead of using a relational database, the application is utilizing DynamoDB. Each article is associated with a specific type: user-id [string][DynamoDBHashKey] ...

The loading on the Express endpoint does not cease, despite configuring the response status (Encountering problems with Multer and Express)

Currently, I am in the process of developing a filter that evaluates a file's signature obtained through a file's buffer provided by Multer. While Multer supplies the MIME type, additional validation methods are required to confirm if the file ma ...

Converting a nested object into JSON using Django serialization

I am faced with the challenge of handling two models in my project: modesl.py class ForumSection(models.Model): title = models.CharField(max_length=20) description = models.CharField(max_length=300) order = models.IntegerField(defa ...