Update current properties of objects

I'm feeling like I'm going crazy and could really use some assistance. My predicament involves a function that looks like this:

private generateTimeObject(firstObject: someInterface, secondObject?: someInterface) {
  let firstTime;
  let secondTime;

  if (condition) {
    firstTime = firstObject.time;
    secondTime = secondObject ? secondObject.time : null;
  } else {
    firstTime = firstObject.someOtherTimeValue;
    secondTime = secondObject ? secondObject.someOtherTimeValue : null;
  }

   firstObject.customValues = {
    firstTimeValue: firstTime,
    secondTimeValue: secondTime
  };
}

So here's the scenario:

The function is called like this: generateTimeObject(firstObject). This means, the function creates a subObject customValues like this:

firstObject.customValues = {firstTimeValue, null}

Then, the function is called again - but this time like this: generateTimeObject(firstObject, secondObject).

This time, the expectation is for the firstObject to be written as follows:

firstObject.customValues = {firstTimeValue, secondTimeValue}

However, I am struggling to make this work. The secondTimeValue remains null, and despite trying Object.assign(), it still doesn't seem to fix the issue.

Any help in solving this problem would be greatly appreciated.

Here's a jsFiddle link. Unfortunately, everything seems to be functioning correctly there, so the problem must be originating from something else. I suspect it may have to do with reference or scope, but I just can't seem to pinpoint the exact cause. https://jsfiddle.net/pna75vrd/6/

Answer №1

Whenever faced with a similar situation like this, my immediate course of action would be to employ a debugger and meticulously step through the code. Alternatively, I could insert console.log() statements strategically to display the variables' values, enabling me to analyze what they are and how they deviate from expected outcomes. Consider the following snippet:

private generateTimeObject(firstObj: anyInterface, secondObj?: anyInterface) {
  let firstT;
  let secondT;
  
  console.log("firstObj=", firstObj)
  console.log("secondObj=", secondObj)

  if (cond) {
    console.log("cond==true")
    firstT = firstObj.time;
    secondT = secondObj ? secondObj.time : null;
  } else {
    console.log("cond==false")
    firstT = firstObj.someOtherValuet;
    secondT = secondObj ? secondObj.someOtherValuet : null;
  }
  
  console.log("firstT=", firstT)
  console.log("secondT=", secondT)

  firstObj.customVals = {
    firstTValue: firstT,
    secondTValue: secondT
  };
  
  console.log("Again, firstObj=", firstObj)
}

My initial hunch is that during the second function call, either secondObj.time or secondObj.someOtherValuet may be null.

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

I am looking to have three rows of input text area comments instead of just one

Utilizing Bootstrap 4.3.1 with React Components I currently have this image: https://i.sstatic.net/rudsE.png And I am aiming for this design: https://i.sstatic.net/VmyTW.png comments: { elementLabel: "Comments", elementType: 'textar ...

Updating the content of a div when the mouse hovers over it

Looking for some help here - I have a few divs with paragraphs of text inside. My goal is to change the text in each div when it's being hovered over. I know this can be done using JavaScript (jquery perhaps?), but my coding skills are pretty basic. A ...

Styling GeoJSON data in the React Leaflet mapping library can greatly enhance the

I successfully incorporated the leaflet map library into my react project. You can check it out here. I also created a geojson map component as shown below: class MapContainer extends React.Component { state = { greenIcon: { lat: 8.3114, ...

activating a button following the selection of a checkbox

My code includes a submit button that is currently disabled. I am looking to enable it when the user clicks on the "I agree" checkbox using jQuery. Can someone assist me with this? My code is written in HTML, JavaScript, and jQuery. <input id="agree" ...

Importing SCSS files dynamically with TypeScript

Recently, I utilized Create React App (CRA) to create a new project and then included node-sass in order to import SCSS files. An example: import "./App.scss"; Although this method works without any issues, I encountered a problem when trying t ...

Generating a new object using an existing one in Typescript

I received a service response containing the following object: let contentArray = { "errorMessages":[ ], "output":[ { "id":1, "excecuteDate":"2022-02-04T13:34:20" ...

Is employing setTimeout a legitimate technique for circumventing a stack overflow issue when implementing callbacks?

Let's imagine a scenario where I deliberately create a complex sequence of callbacks: function handleInput(callback) { ... } function fetchData(url, callback) { ... } function processResponse(callback) { .... } function updateDatabase ...

What is the method for retrieving values from an object using keys that are subject to change?

Here is the code snippet I am working with: bodyLength.forEach((el, i) => { console.log(`${values.bodyTitleEn2 + i.toString()}`); body.push({ title: [ { key: 'en', value: values.bodyTi ...

The vertical tabs in JQueryUI lost their functionality when a few seemingly unrelated CSS styles were added

Check out the JsFiddle demo here I embarked on a mission to craft JQueryUI Vertical tabs by following the guidance provided in this example. The source code within the aforementioned link contains specific CSS styles: .ui-tabs-vertical { width: 55em; } ...

Navigating with Angular's router occurs before the guard is fully completed

Within my Angular 8 application, the routing file is structured as below: const myRoutes: Routes = [ {path: '', component: FirstComponent , canActivate: [RegistrationSrcdGuard]}, {path: 'FirstComponent ', component: FirstCompon ...

Error: The term "require" is not recognized in the context of the React

After creating my own React component as an NPM package and publishing it on NPM, I encountered an error when trying to import and use it in other Create React App (CRA) projects. The error occurs when running npm start in the command line. See the screens ...

Navigating the authorization header of an API request in a Node environment

const authHeader = req.headers["authorization"]; I have a question that may come across as basic - why do we use ["authorization"] instead of just .authorization? After some research, I discovered it had to do with case sensitivity but ...

Is there a way to inform the List component when the height of its row items has been altered in order to trigger a rerender

In my project, I am using a react-virtualized List where each item in the rows has an expand button. When this button is clicked, the row's height changes to reveal more information. The problem I am facing is that after clicking the button, the inne ...

Can a website built on Express.js be optimized for SEO?

Would pages created with the traditional route structure provided by Express (e.g. ) appear on Google's Search Engine Results Page as they would for a Wordpress blog or PHP website using a similar path structure? ...

What is the Typescript definition of a module that acts as a function and includes namespaces?

I'm currently working on creating a *.d.ts file for the react-grid-layout library. The library's index.js file reveals that it exports a function - ReactGridLayout, which is a subclass of React.Component: // react-grid-layout/index.js module.exp ...

Exploring the possibilities of integrating JSONP with Framework7

I've been attempting to retrieve images from the Instagram public API using ajax and JSONP: var target = https://www.instagram.com/p/BP3Wu_EDXsjdT5Llz13jFv2UeS0Vw0OTxrztmo0/?__a=1?callback=?'; $$.ajax({ ty ...

Issues with loading JavaScript in Selenium

I have been trying to extract data that is loaded through google tag manager. Despite my efforts using both chrome and firefox, the li elements I need in the body always appear empty no matter what timing I use. import undetected_chromedriver as uc from ...

Utilizing and transmitting contextual information to the tooltip component in ngx-bootstrap

I am currently working on integrating tooltips in ngx-bootstrap and trying to figure out how to pass data to the ng-template within the tooltip. The documentation mentions using [tooltipContext], but it doesn't seem to be functioning as expected. Belo ...

Ways to retrieve all elements, including those that are hidden, within a CSS grid

My goal is to retrieve all the "Available Items" using Javascript in one go. However, I am facing an issue where not all of them are visible at once due to the need to manually scroll through a CSS grid. <div class="gridWrapper" data-dojo-attach-point= ...

Protractor's browser.wait function is not functioning properly when conducting tests on a non-AngularJS website

I am currently working on testing a non-angular JS website using Protractor. Even though my test case passes successfully, I am looking to eliminate the sleep statement and replace it with either a wait or Expected condition in my test case. Here is a sni ...