What is the best way to update a nested property in an object?

Consider the following object:

myObject{
       name: '...',
       label: '...',
       menuSettings: {
          rightAlignment: true,
          colours: [...],
       },
    }
    

I want to change the value of rightAlignment to false without altering the rest of the object. I attempted to use myObject.find(...) but it didn't work as expected. Then I tried

Object.assign(this.myObject, {menuSettings: {rightAlignment: false}});
    

However, this approach did not access the property correctly. Is there a cleaner way to accomplish this?

Edit: I discovered that the array I was attempting to modify actually contained multiple objects. The solution that worked for me was iterating over each myObject in the array and checking if menuSettings existed (as it was an optional property that sometimes wasn't present).

If menuSettings existed, I would then:

this.myObject.menuSettings.rightAlignment = true;
    

Answer №2

You're almost there. It seems like you're trying to combine an existing object with the most up-to-date values from another object. To achieve this, you can use the following method:

myObject.menuSettings = Object.assign({}, myObject.menuSettings, { rightAlignment: false });

The approach you are currently using is not incorrect. However, by replacing the entire menuSettings, you might lose the menuSettings.colours.

Alternatively, you can directly access the property as suggested by Alexander.

var myObject = {
   name: '...',
   label: '...',
   menuSettings: {
      rightAlignment: true,
      colours: ['...'],
   },
}

myObject.menuSettings = Object.assign({}, myObject.menuSettings, { rightAlignment: false });

console.log(myObject)

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

Is there a way to utilize a Javascript function to incorporate commas into a div tag?

Being new to JavaScript, I have heard about jQuery but I don't know how to use it. Please bear with me as I am not well-versed in this area. :) I am currently importing data dynamically from an Excel database to a website. Everything is working fine ...

Showing a pop-up dialog box once a value has been selected

When the ajax autocomplete value is selected in a certain textfield, I want to display a message box. To achieve this, I am utilizing the jquery-confirm JavaScript library which can be found here. Below is my code snippet: select: function( event, ui ) { ...

Tips for showing ng-repeat items solely when filters are applied by the user

Is there a way to only display elements when a user uses a filter? For instance: $scope.elements = [{name : 'Pablo', age : 23}, {name : 'Franco', age : 98}]; <input type="text" ng-model="searchText" /> <div ng-repeat="elemen ...

Issue encountered while rendering tables with Jquery-dataTables

Encountering an issue with jquery datatables when fetching data from a URL using ajax calls. Implementing the codeigniter framework, I utilize the datatables library to create datatable objects by invoking the echo $this->datatables->generate() metho ...

Dynamic data binding in AngularJS with dynamically generated views

The scenario: Currently, I am constructing a wizard in AngularJS that contains tabbed content with each tab representing a step in the wizard. These steps are fetched from the database through a Laravel controller and displayed using ng-repeat. Each tab c ...

Tomcat hosting a dynamic duo: Spring Boot and React!

Exploring the world of Spring Boot application development with a React client using Gradle is an exciting journey for me as I navigate through these new technologies. My current progress includes successfully creating a WAR file that encompasses several i ...

preventing further executions by halting a function after the initial click

I've come across this function: function display() { $.ajax({ url: "new.php", type: "POST", data: { textval: $("#hil").val(), }, success: function(data) { ...

Completed Animation with Callback in AngularJS CSS

Currently working with AngularJS and hoping to receive a notification upon completion of an animation. I am aware that this can be achieved with javascript animations such as myApp.animation(...), but I'm intrigued if there is an alternative method wi ...

What is the correct way to display or hide a button based on my specific situation?

Creating a 'show more' button for my app has presented me with a challenge. I am using a directive to handle actions when the user clicks on the read more button: (function(window, angular) { var app = angular.module('myApp'); ...

Create the Smallest Possible Number by Eliminating n Digits from a Specified Number

In this algorithm, a number (as a string) is input and the goal is to remove n numbers in order to obtain the lowest possible resulting number. It's important to maintain the original order of the numbers while removing them. To achieve an O(n) effic ...

Pressing the icon will trigger a top-sliding dropdown mobile menu to appear

How can I ensure my mobile dropdown menu slides in from the top when the user clicks the "header-downbar-menu" icon and slides out to the top when clicked again? Currently, the button only shows the menu but I am struggling with writing the JavaScript for ...

Accessing data attributes using AngularJS

Trying to extract the data attribute from the following code: <button ng-click="EditPlayer(name, position, number, age)" id="btnEdit" class="btn btn-successes" data-playerid="{{player.id}}">Save</button> Within my angular controller: $scope. ...

Issue with Ionic and Angular: Struggling to empty input field

Within my Ionic app, there is a form that contains an input field and a button. Upon clicking the button, an action should occur within the controller to clear the input field. Unfortunately, this functionality is not working as expected. Despite its simpl ...

Expanding a Node.js class to incorporate additional static class elements

I have a query where I believe that extending a class might be the solution, but I am not entirely sure. Here is the scenario... There is a class defined as follows: class Field { apiName; /** * Creates an instance of Field with the given par ...

Guide on incorporating one element into another with jquery

I am facing a challenge with the following code snippet: <p>Nuno</p> <p>Eimes</p> My goal is to transform it into this format: <p><a href="name/Nuno">Nuno</a></p> <p><a href="name/Eimes">Eimes& ...

What is the best way to create vertical spacing between Material UI Grid Paper components?

The spacing of the goal components is not as I would like it to be. This is how they currently appear. https://i.stack.imgur.com/jApzK.png So far, I have attempted setting the display of the Paper selector to flex. Additionally, I experimented with adjus ...

RadAjaxNamespace is not found within the codebase

While testing the application on my development machine, I encountered an error message in the browser debug console stating "RadAjaxNamespace is not defined". Interestingly, this error does not appear when accessing the production server. Upon comparing t ...

The error message "TypeError: res.response is undefined" is indicating

Currently, I am implementing user authentication using JWT auth within a Vue/Laravel single-page application. The problem arises in the register module as it fails to respond upon clicking the button. Upon inspecting the Firefox developer edition's co ...

There appears to be a malfunction in the socket rooms, as they are not operating

I have set up a code where sockets are being sent to the wrong person, and I am unable to figure out why. Whenever I update one user's status, it also updates the other user's status. Snippet of Code io.on('connection', function(socke ...

Issue: Unable to find a compatible version of chokidar. Attempted chokidar@2 and chokidar@3 after updating npm to version 7.*.*

After using ejected CRA, it compiled successfully but then broke with the following error. The issue started to occur after updating npm from version 6 to 7. You can now view webrms in the browser. Local: http://localhost:3001 On Your Netw ...