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

Troubles encountered while parsing nested JSON objects with a streaming parser

I'm currently using the code provided in this helpful resource for parsing my JSON: Although it successfully handles most of the JSON data I have, it encounters issues when a JSON object is directly nested as a child within another one. To illustrat ...

Looking for guidance on where to find a functional code sample or comprehensive tutorial on working with ViewMetadata in Angular2

I am currently trying to understand the relationship between viewmetadata and the fundamental use of encapsulation: ViewEncapsulation, including ViewEncapsulation.Emulated and ViewEncapsulation.None. Here is a link for further information: https://angula ...

Utilize mapGetter and mapMutations in Vuex with TypeScript without the need for class-style components syntax

After completing a project in Vue, I found myself getting a bit confused without static types. To address this, I decided to incorporate TypeScript into my project while still maintaining the traditional way of writing code, without classes and decorators. ...

Retrieving properties of a universal function

I am facing a challenge in creating a class that accepts a factory function as one of its parameters in the constructor, which is then used to create instances of another class. The implementation below is written in JavaScript. // item to create class Ite ...

Utilize CountUp.js to generate a dynamic timer for tracking days and hours

I am looking to create a unique counter similar to the one featured on this website https://inorganik.github.io/countUp.js/ that counts up to a specific number representing hours. My goal is to display it in a format such as 3d13h, indicating days and hour ...

Preventing input in one textbox if another textbox has a filled value in HTML

Apologies for asking this question, but is there a way to disable one text box if another text box has a value? I've attempted using the following code, but it doesn't seem to work. Sorry for the inexperienced inquiry T_T function disableTextbox ...

Using JSON_ENCODE may attempt to evade double quotes

I have a controller that retrieves data from my database, formats it as valid JSON, but the HTTP response is text/html instead of application/json. This causes issues with getJSON not working properly. Should getJSON work regardless? public function send ...

A method for performing precise division on numbers in JavaScript, allowing for a specific precision level (such as 28 decimal places)

I've searched extensively for a library that can handle division operations with more than 19 decimal places, but to no avail. Despite trying popular libraries like exact-math, decimal.js, and bignumber.js, I have not found a solution. How would you ...

Unlocking the Secrets of Deserializing JSON Entities

I am experimenting with utilizing the get request like so: req = Net::HTTP::Get.new("/api/v1/users/external/1/features/DOWNLOAD7ab8d82b40/alloc?paymentPlanId=PRO_SUBSCRD725FCCCC6"); req.add_field('ISV_API_KEY', '548f3d4b34ffdb2f294a870a ...

Prevent infinite scrolling with JavaScript AJAX when the response is empty

I am currently implementing the infinite scroll functionality on my website. Whenever the page reaches the bottom, an ajax call is triggered to fetch a new set of data. However, I'm unsure how to handle stopping the ajax call if there is no more data ...

What is the best way to simulate a constructor-created class instance in jest?

Suppose there is a class called Person which creates an instance of another class named Logger. How can we ensure that the method of Logger is being called when an instance of Person is created, as shown in the example below? // Logger.ts export default cl ...

Is it possible to use Material-UI Link along with react-router-dom Link?

Incorporating these two elements: import Link from '@material-ui/core/Link'; import { Link } from 'react-router-dom'; Is there a method to combine the Material-UI style with the features of react-router-dom? ...

Determine the width of the window and adjust the positioning of jQuery UI tooltips accordingly

Struggling to adjust the jQuery UI tooltip position based on screen width, but can't seem to figure it out. Can someone assist me in detecting the browser's width and changing the tooltip position accordingly? [fiddle] $(function () { $(doc ...

What is the best way to expose the "nuxtServerInit" action for Nuxt.js when using dynamic modules exclusively?

According to this answer, the code snippet below is taken from the official documentation of vuex-module-decorators // @/store/index.ts import Vuex from 'vuex' const store = new Vuex.Store({ /* Ideally if all your modules are dynamic then ...

Step-by-step guide for embedding a Big Commerce website into an iframe

Can a website be opened inside an iframe? If not, is it possible to display a message like 'page not found' or 'this website does not allow data fetching in iframes'? <!DOCTYPE html> <html> <body> <h1>Using the ...

Ajax request (with Spring) causing HTTP error 415Charsets deems invalid

My server doesn't receive a response when I send an Ajax request. PUT request: function modifyData() { var item={ id:idNum.replace('edit',''), data:newData }; console.log(item); ...

The function window.close() does not close the pop-up window when called within the pop-up

I am facing an issue with a Customer Info form that contains an anchor tag "close" meant to close the current window. This customer form is displayed as a pop-up. Within this form, there is also a search button that triggers a pop-up for the search form co ...

The jQuery form validator doesn't seem to work with AJAX for me, but I've figured out how to make jQuery validate without using

I have been facing an issue with my code that involves the jquery validator and ajax. The code seems to validate properly and the serialize() function appears to be working as I can see the data in the browser. However, the problem arises when the data d ...

Utilize the gsap ScrollTrigger in conjunction with React's useRef() and Typescript, encountering issues with type mism

Recently, I've been trying to add some animation to a simple React Component using the GreenSock ScrollTrigger plugin. However, I ran into an issue due to types mismatch in my Typescript project. Here's a snippet of the code: import React, {useRe ...

Can you explain the error message "a.split is not a function" in an Angular context?

My Angular application is encountering an error upon page load. The error message displayed is as follows: angular-amin.js:122 TypeError: a.split is not a function at r (angular-amin.js:186) at m.$digest (angular-amin.js:145) at m.$apply (angular-ami ...