JavaScript Dynamic Object Keys

Hi there,

Whilst I have been learning react, setting an object key dynamically using the square notation [] was something that tripped me a lot, especially when it came to forms and state updates. Therefore I'd like to share my understanding of it and hopefully someone may find it helpful. syntax [keyVar] = keyName; Example 1:

 const dataFromAPI = 'location';
 let person = {
    name: 'susu',
    age: 22,
    job: '',
    [dataFromAPI]: 'Spain'
//{ name: 'susu', age: 22, job: '', location: 'Spain' }

In the above example, using the square brackets lets us assign the variable in the object literal dynamically. What is important to note is: when using square brackets [] we are not setting a keyName equal to a variable, instead, we are setting it equal to whatever value we have in the variable. The value of the variable becomes the key name. console.log(person.location) //Spain

example 2: using a function to dynamically update the object

let updateObject = (key,value)=>{
    person[key] = value
//{ name: 'Greg', age: 22, job: '', location: 'Spain' }

When the above function is called, the key in person with the 'name' property gets its value changed to whatever value was passed as the second argument to the updateObject function call.

example 3: If the key/value passed to the updateObject method doesn't exist in the person object, it gets added automatically

// {
//     name: 'Greg',
//     age: 22,
//     job: '',
//     location: 'UK',
//     skills: [ 'JavaScript' ]
//   }

This post is mainly to show the dynamism of Object keys, and my first attempt at technical writing, let me know if you have any feedback.

Avatar for Fatima Aminu

Written by Fatima Aminu


Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.