Changing a complex object within a nested array of a BehaviorSubject

I'm currently working on an Angular app. Within my service, DocumentService, I have a BehaviorSubject that holds an array of Documents.

documents: BehaviorSubject<Document[]>

Let me provide you with some insight into the various classes I've created:

class Document {
  title: string
  files: File[];
}

class File {
  pages: Page[];
}

class Page {
  content: any;
  resolution: number;
}

Now, here's my dilemma - what is the most effective way to update the resolution property within a page? To achieve this, I need to navigate through the document, access the file, and then reach the specific page for modification. Unfortunately, directly updating in place isn't an option due to the requirement of using

this.documents.next(newDocumentsArray)
. I've tried deep copying methods like JSON.parse(JSON.stringify(...)), but encountered issues with circular structures. Other techniques such as .map and Object.assign only provide shallow copies that end up modifying the page directly, which is not permissible in this case.

Any suggestions or advice would be greatly appreciated. Thank you!

Answer №1

To maintain your current deep structure, you'll have to dive deep into the code:

const updatedDocuments = oldDocuments.map(document => {
  if (document !== documentToUpdate) {
    return document;
  } else {
    return {
      ...document,
      files: document.files.map(file => ({
        ...file,
        pages: file.pages.map(page => {
          // implement page changes here
        })
      }))
    };
  }
});

I recommend transitioning to a flat Entity-style structure, where each Document, File, and Page is stored with a unique ID in separate dictionaries. The Document's files array would contain the IDs of its Files, and similarly for Files referencing their Pages. Does this approach resonate with you?

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

forming an instance from JSON information

In a .json file, I have data that includes information on countries such as their currency, major language, and land area in square kilometers or square miles. { "countries": { "sweden": { "currency": "Swedish krona", " ...

It is impossible for Javascript to access an input element within a gridview

I have developed an asp.net page that allows a site administrator to select a user as the 'systems chair'. The page displays users in a gridview and includes a column of radio buttons to indicate who the current chair is or to change the assigned ...

Learn how to resubscribe and reconnect to a WebSocket using TypeScript

In my Ionic3 app, there is a specific view where I connect to a websocket observable/observer service upon entering the view: subscribtion: Subscription; ionViewDidEnter() { this.subscribtion = this.socket.message.subscribe(msg => { let confi ...

Solving the Angular form glitch: error message not displaying

I am facing an issue with my simple form where I am not able to display errors related to the fields. <html lang="en" ng-app="MyApp"> <head></head> <body ng-controller="AppCtrl"> <form name="myForm" id="myForm"& ...

The JavaScript date picker is malfunctioning in the HTML editor, but it functions properly in Fiddle

I have a working format available in a JS fiddle. Here is the code I have used on my demo site: I created a new folder named "js" and placed datepicker.js inside it, then linked it in my HTML like this: <script type="text/javascript" src="js/datepicke ...

Material-UI: Creating Radio Button Groups

I have been working on a project using React and Bootstrap. I decided to switch to material-ui, which went smoothly except for the radio buttons. Below is the original code that worked well: <label> <input type={that.props.questionType} name ...

Send the Post model along with 2 checkbox lists to the controller using Jquery's Ajax function

How can I efficiently send 2 lists containing values of checked checkboxes along with my model using JQuery Ajax from an EditorTemplate used as a partial view? Here's the code snippet: @model EsdpExport.View_Models.ProductLineCreateViewModel @using E ...

Identify the mouse's location in relation to its parent element, not the entire webpage

A script I've been working on detects the mouse position relative to the page, taking into account a movement threshold of 100px before triggering certain actions. // Keep track of last cursor positions var cursorDistance = 0; var lastCursorX = null; ...

Exploring the object structure received from AngularFire

Here is the Firebase query that I am running: var ref = new Firebase('https://<myfirebase>.firebaseio.com/companies/endo/status'); data = $firebaseObject(ref); console.dir(data); The object that I receive looks like this: d ...

Utilizing X-editable in an ASP MVC View: navigating the form POST action to the controller

I have been utilizing the X-Editable Plugin to collect user input and perform server submissions. However, I am encountering an error during submission. What adjustments should I make in order to ensure that the x-editable data functions properly with the ...

Obtain real-time information from an object using React

After developing an app using React, I encountered a scenario where I needed to work with data from an API. Here is the object structure: let currency = { "success": true, "timestamp": 1648656784, "base": "EUR", &quo ...

Unable to modify existing attributes in a sails.js model

I'm new to sails.js and I have a question about adding fields to an existing model in Sails.js. Here is the current model: module.exports = { attributes: { id: { columnName: 'id', type: 'integer&apos ...

Having trouble getting routing to function properly with react-router-dom

I'm currently assisting a friend with completing a React Project. I'm facing an issue while trying to set up routing using react-router-dom. The components inside the <switch> tag are not functioning properly. Below are snippets of my code: ...

Troubleshooting steps for resolving a node.js error during execution

I recently delved into server side programming with node.js, but I'm encountering some issues when trying to execute it. My server is set up at 127.0.0.1:80, however, I keep running into errors. Console: Server running at http://127.0.0.1:80/ node:ev ...

Encountering RxJS errors during the process of constructing an object using streams retrieved from Firebase

I am currently in the process of developing a template-driven form that involves multiple streams from Firebase. Despite my efforts, I keep encountering errors with the json pipe. The error message I receive is "Converting circular structure to JSON as ...

Live search bar feature with jQuery更新

I am currently working on creating a dynamic search bar that updates a list of items from the database based on the input value. Below is the code I have developed for this search bar: $(document).ready(function(){ $('#search').keyup(function ...

The issue arises with getInitialProps as it fails to pass data to the page component while attempting to retrieve initial information and subsequently modify it using a button

I am currently working on a component located at app\page.tsx in Next.js v13.4.12, and it includes a button. My goal is to have the button trigger the handleClick function when clicked. The issue I'm facing is that the getInitialProps function ...

Deactivate tag Script using JQuery

Is there a way to dynamically remove two <script> tags from a page at the document ready event? Each tag is assigned its own unique id. I attempted to use the following code: $("#idPrimoScript").remove(); $("#idSecondoScript").remove(); However, t ...

Accessing array values depending on DOM response

Generate a string from selected DOM elements I have an object that contains months and their corresponding index numbers (not dates) monthList = {"jan" : "1", "feb" : "2". etc: etc} The user can input values like jan or jan,feb,march and I need to return ...

What are the distinctions in type-narrowing when assigning values using ternary expressions versus if-else statements?

It seems that the type checker is handling the typing of m in print() differently based on whether m was assigned through a ternary expression or an if-else statement. What sets apart the first line in the print() function from the commented code below it? ...