Jessie Anderson
Jessie Anderson

Reputation: 319

How to use dynamic property in object

I have a handleInputBlur function that has a dynamic parameter. Say I have this.props.user object like this

{ name: 'abc', age: 10 }

Then in my UI I can do inline edit, so handleInputBlur will get a parameter of name changeField which will be an object containing the changed field:

{ age: 10 }

I still have to pass the entire object back to the backend, how can I replace updated field with my existing object?

I tried this but got an Unexpected Token error:

handleInputBlur = (changedField) => {

    const existingUser = this.props.user

    const updatedUserObj = Object.assign({}, existingUser, {
        existingUser[changedField]: changedField
    })
}

How can I update the existing user based on changedField's key and value?

Upvotes: 0

Views: 61

Answers (1)

Andrew Li
Andrew Li

Reputation: 57934

Use computed property names by surrounding the key that is an expression with brackets so its computed value is used as the key:

const key = Object.keys(changedField)[0];
const updatedUserObj = Object.assign({}, existingUser, {
    [key]: changedField[key]
})

First, the value of the expression key will be computed, then that value would be used as the key. Notice that Object.keys(changedField)[0] is the value of key. What this does is get the first key inside the changedField object -- the property being changed such as 'name' or 'age'. Then, that property is set to the value of the new property by accessing the value of the first key in changedField.

Upvotes: 1

Related Questions