Home > Net >  How to dynamically update an object field in JavaScript/TypeScript
How to dynamically update an object field in JavaScript/TypeScript

Time:11-17

I have a method for handling an update on this object. In this method I want to accept any field value that the object has, such as name, age, weight, eyeColor etc. If that field exists within that object, I'd like to be able to update the object dynamically for any field they pass in.

I am currently doing it incorrectly I believe with the spread operator while trying to update one field in the object. There is an error that fieldName does not exist within myObject. Does anyone know how to do this dynamically without need for a long switch statement checking each of the fields against fieldName passed in? In previous attempts tweaking with this I have successfully added a new field to the object named "fieldName" which is also not what I wanted.

If anyone has any ideas, that would be so helpful, 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'); // Want this call to update the name of 'John' to 'Jack'

CodePudding user response:

In short, you're looking for:

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

You can make a generalized, typesafe function to do this as follows:

function updateProp<TObj, K extends keyof TObj>(obj: TObj, key: K, value: TObj[K]) {
    return {...obj, [key]: value};
}

and call it as follows:

const foo = { a: 1, b: "monkey" };
const updatedFoo = updateProp(foo, "b", "hello world")

Playground Link

CodePudding user response:

You're looking for the Bracket notation property accessor:

myObject[fieldName] = fieldValue

Compared to the approach with the spread operator, this does actually update the object in place. I.e. if the reference in myObject was previously copied elsewhere, that reference will also "see" the updated field. Whereas, by overriding the value with myObject = {...myObject}, you're creating a new object each time.

  • Related