Tips for dynamically modifying a property of an object in JavaScript/TypeScript

Looking for a way to dynamically update any field in an object? I have a method that aims to do just that. Whether it's the name, age, weight, or eye color of the object, I want to be able to pass in any field and have it updated accordingly.

Currently, I'm using the spread operator but encountering issues when trying to update a single field. There's an error stating that the fieldName doesn't exist within myObject. Is there a way to achieve this without resorting to a lengthy switch statement to check each field against the passed-in fieldName?

If you have any suggestions or ideas on how to accomplish this dynamically, I would greatly appreciate it. Thank you!

let myObject = {
    name: 'John',
    lastName: 'Smith',
    age: 26,
    weight: 200,
    eyeColor: 'blue',
    hairColor: 'blonde'
};

const handleUpdate = (fieldName: string, fieldValue: string | number) => {
    if (fieldName in myObject) {
        myObject = {...myObject, fieldName: fieldValue};
    }
}

handleUpdate('name', 'Jack'); // Hoping for this call to change the name from 'John' to 'Jack'

Answer №1

Simply put, what you're seeking is:

{...myObject, [fieldName]: fieldValue}

To achieve this in a more generalized and type-safe manner, you can create a function like so:

function updateProperty<TObject, Key extends keyof TObject>(obj: TObject, key: Key, value: TObject[Key]) {
    return {...obj, [key]: value};
}

You can then use it as demonstrated below:

const sampleObject = { a: 1, b: "apple" };
const updatedObject = updateProperty(sampleObject, "b", "hello friends")

Interactive Example Here

Answer №2

If you want to access object properties using bracket notation in JavaScript, you can do it like this:

myObj[key] = value

Using bracket notation allows you to update the object directly, maintaining references to the original object. However, if you create a new object by spreading the original one like myObj = {...myObj}, each time you will get a completely new object instead.

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

Simulate a failed axios get request resulting in an undefined response

I'm having an issue with my Jest test mock for an axios get request, as it's returning undefined as the response. I'm not sure where I might be going wrong? Here is the component with the axios call: import {AgGridReact} from "ag-grid- ...

Tips for sending a variable to the onclick function within an HTML element

Currently, I am utilizing the tabulator library to generate tables based on json data. I am attempting to insert a button into a cell using a custom cell formatter. Below is the approach I am taking: var graphButton = function(cell, formatterParams, onRe ...

Having trouble locating the 'tsc-watch' module due to the missing 'typescript/bin/tsc' when running the TypeScript compiler

Encountering the error "Cannot find module 'typescript/bin/tsc' when attempting to run tsc-watch yarn tsc-watch --noClear -p tsconfig.json yarn run v1.22.19 $ /Users/jason/Work/VDQ/VDQApp/node_modules/.bin/tsc-watch --noClear -p tsconfig.json Ca ...

Is Express capable of serving static files from a hidden folder with dot file?

I have set up my app to serve a static folder in the following way: app.use('/static', serveStatic(__dirname + '/view/my/static/folder')); Now, I am wondering how to configure the server to serve a hidden folder. For example, if I hav ...

Is it better to load AngularJS partials at the start instead of waiting until they are needed in Django?

In my Django project, I have a template folder where all the templates and partials for my app are stored. Instead of loading each partial individually based on controller requests in Angular, I want to preload all the partials into the template cache at t ...

Utilizing PhP and AJAX for seamless form uploads without the need to refresh the page

I have a form in PHP that reloads after submission. I implemented Ajax to prevent the reloading, but now the data is not being submitted to the database. Am I overlooking something here? When I remove the AJAX, it functions properly but reloads the page. I ...

What steps should I take to fix the 'no-undef error in my React application where 'Component' is not defined?

Header.js import React, { Component } from "react"; class Header extends Component { state = {}; render() { return ( <> <div> <header className="navbar navbar-expand-lg navbar-dark bg-dark" ...

Is it possible to set up TypeScript npm packages to be installed in their original TypeScript format rather than JavaScript for the purpose of examining the source code?

Despite my lack of expertise in the inner workings of how a TypeScript library compiles itself to JavaScript before being placed in the node_modules directory, I have a question: Coming from a PHP background, I am accustomed to being able to explore any l ...

Set up a listener to detect changes in fullscreen mode for the specified host

How can I determine if the fullscreen mode is active using the HTML5 fullscreen API with Chrome and Angular 4.x? I have developed an Angular component and included the following @HostListener: @HostListener('document:webkitfullscreenchange', ...

Is there a way to retrieve the text of a clicked button with execute_script?

Is there a way to extract text from a clicked button and send it back to Python? The user clicks the button in the Selenium WebDriver browser using the mouse. This is what I attempted: x=driver.execute_script("$(document).click(function(event){var te ...

Issue with setting .mtl properties in a custom shader in three.js

In my custom three.js application, I am loading an OBJ/MTL model for rendering. I am trying to apply a custom shader to the model, but the color and specular uniforms that I manually pass to the RawShaderMaterial are not updating correctly. Instead, they a ...

What is the best method for incorporating success icons into my website with vue.js?

Hey everyone, please excuse my lack of expertise as I am a beginner in this field. I'm trying to incorporate success icons into my website using bootstrap or similar tools, but I'm unsure of how to implement the if statement below. If anyone co ...

Fetching image files from Angular JS in a servlet

On my website, users have the ability to upload images. I am using AngularJS to post the data to a specific URL via a POST request. My question is, how can I retrieve this data in a Java servlet? My goal is to save the uploaded image in a database. Is this ...

Preventing file visibility in Three.js resource directory

Once a user clicks on a specific 3D model, I retrieve it from the server and render it in the browser using three.js. However, there is an issue when the user tries to access a model that is not free - they can easily view and download the STL file by go ...

JQuery class for swapping elements upon scrolling

I am currently working on a navigation bar that changes classes to create a fading effect for the background. The approach I have taken involves targeting the window itself and monitoring the scroll position of the user. If the user scrolls down more than ...

Error message stating 'is not recognized' caused by Angular SharedModule

I have a navbar component that I've organized into a module called 'NavbarModule' so that it can be easily shared. My goal is to use this component in the 'ProductsListComponent'. However, even after properly importing and exportin ...

Extract targeted content from a webpage

I'm in need of assistance with printing a specific section of my application. Within the application, there is a user list that shows their first and last names. When I click on a user, a popup displaying more detailed information about them appears. ...

"Adding an express route after your app has already started listening - a step-by-step guide

I am looking for a way to automatically set up routing in Express. Currently, I am able to scan a directory and manually add routes from all the available files. These routes can also be updated if changes are made in the route file. delete require.cache[ ...

Fixing Null Pointer Exception when Posting Form Data using Jersey MultiFormData in JavaScript

I'm currently attempting to send form data using JavaScript to a Jersey Resource. The JavaScript code I have is as follows: var form = document.getElementById('form'); var formdata = new FormData(form); if (window.X ...

Utilize strings as object keys in JavaScript

Let's say I have the following variables: var myKey = "This_is_my_key" var myObj = {"This_is_my_key" : true} What is the proper way to access myObj using the key myKey? ...