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

The Ajax query returned a successful response, yet it unexpectedly triggered an error

Currently, I am delving into the realm of mongodb. I have integrated Express, Body-Parser, and Mongoose into my project, and I'm retrieving data from an online mongodb database hosted on mlab. Everything seems to be functioning smoothly as I've t ...

What is preventing my boolean from being altered?

Creating a basic calculator that can handle single-digit arithmetic. The current code is incomplete and redundant, so please avoid commenting on that. <!doctype html> <html> <head> <title>JavaScript Learning Zone</title> ...

What is the most effective method for exchanging variables between programs or threads?

I currently have a program that executes an algorithm processing real-time data. Once per hour, the algorithm's parameters are optimized based on new historical data. Currently, this optimization process is running in a single thread, pausing the rea ...

Is it possible to disregard any spaces within the content of an <option> element?

In my current project, I am facing an issue where a Django server is sending JSON data to a template with Vue.js running on it. The problem arises from the fact that some values in the JSON data have trailing spaces, causing complications. I am looking for ...

What's the best way to update the value of a TextInput field?

Previously, I was updating the text input using local state. Here's an example: state = {name: ''} ... <AddEditFormInputs onChangeText={name => this.setState({ name })} textStateValue ...

Is it possible to transfer a specific feature from jQuery to Prototype?

I find myself in a situation where I have to use Prototype instead of jQuery, even though I'm not as familiar with it. Can anyone assist me in transforming the following script: var output={}; $$('ul li').each(function(item){ var firstL ...

Guide to creating two-way data binding using ngModel for custom input elements like radio buttons

I am currently facing an issue with implementing a custom radio button element in Angular. Below is the code snippet for the markup I want to make functional within the parent component: <form> <my-radio [(ngModel)]="radioBoundProperty" value= ...

What is the best way to convert $('input[type=text]') into vanilla JavaScript?

How can I change this to plain JavaScript? I've been struggling to find a solution, any pointers? ...

Can an onload function be triggered within the location.href command?

Can a function be called onload in the location.href using jQuery? location.href = getContextPath() + "/home/returnSeachResult?search=" + $('#id-search-text-box').val() + "&category=" + $('#search_concept').text() + "onload='j ...

The success variable of the Ajax running continuously in a loop is not being refreshed

Within this code snippet, a for loop is utilized to iterate through an array called netnos[] and update the variable 'nets' for each item. Ajax is then invoked to call a PHP script that generates a listing, which is successfully outputted to the ...

React Native: struggling to fetch the most up-to-date information from an array

I'm working on a chat application that functions similar to a chatbot. Since I don't want to use a database and the messages are temporary, I opted to utilize JavaScript arrays. Whenever a user inputs a message in the TextInput and hits the butto ...

Accessing data from a complex JSON structure

Hello all, I am currently attempting to extract the subject name value from a JSON file called dataArray that has already been processed through NSJSONSerialization: -0: { id: "55edc05848177ec741daf79e" firstName: "Brad" rating: 4.2 lessons: 5 text: "Les ...

Is it possible to assign binary content to the src attribute of an img, audio, or video tag?

Picture this scenario: I send an ajax request to my PHP server with the name of an image file, and the server is restricted from sending a direct link to the file. Instead, it must send the file contents using PHP's readfile(); function. Now, when thi ...

Comparison of various nodejs scripts

Snippet One net.createServer(function(socket){ socket.on('data',function(id){ getUserDetails(function(){console.log(id)}); }); }); function getUserDetails(next){ next(); } Snippet Two net.createServer(function(socket){ ...

Each block in Svelte includes a unique shorthand attribute

I have a JSON variable that holds attributes in a specific structure: // This json variable defines the attributes for elements to be created let myElements = [ { attr1: "myAttr1", attr2: "myAttr2", }, { ...

Error: Attempting to update the value of 'ordersToDisplay' before it has been initialized in a re-render of React. This results in an Uncaught ReferenceError

Trying to dynamically update the document title to include the order number by clicking a button to display different numbers of orders from an array on the screen. The process involves importing a JSON file, filtering it based on user input, calculating ...

Showcase fullcalendar events that span across multiple rows and columns

Within my Angular application, I am utilizing the Angular UI Calendar in conjunction with Fullcalendar to display user events. Currently, when a user interacts with an event by clicking on it, only a portion of the event is highlighted. This becomes probl ...

Transform the image data retrieved from an external API into the appropriate format for displaying on the webpage

When I make a call to an external API, it returns image data that I want to render on my page. However, the response looks like this when I log it to the console: https://i.stack.imgur.com/GpDhH.png I'm not very familiar with image formats, so I&ap ...

Python program to find the common elements in two arrays

I am currently working with two arrays and my goal is to create a new array that represents the intersection of the original arrays. Both original arrays need to have the same length. For instance, if I start with: arr1 = np.array([(255, 255, 255), (255, ...

How does Ruby on Rails facilitate interactions between multiplayer users and visitors?

I am looking to create a way for visitors to interact on my website. Imagine a virtual chat space. This involves collecting and sharing data among users, which can be accomplished using ajax or similar methods. However, I'm wondering if there are ex ...