Dynamic Fields in JavaScript Objects

Dynamic Fields in JavaScript Objects

Hello folks! This blog is a beginner-friendly explanation of dynamic fields in JavaScript Objects.

Let's start from scratch.
An object in JavaScript looks like this:

const todaysMeals = {
breakfast: "Maggi", 
lunch: {
     roti: "Butter Naan", 
     vegetable: "Paneer Tikka Masala"},
dinner: "Soup"
}

Objects in JS have key/value pairs known as properties.

The keys are essentially treated as strings whereas the values can be anything from all the primitive values, objects to functions.

We can access the properties of the objects in two ways:
1. Dot Notation
2. Bracket Notation

  1. Dot Notation

In dot notation, we simply take the name of the object and access the key in it with a dot. So it's objectName.keyWeWantToAccess

Let's try to access "Maggi" and "Butter Naan" in the above object.

console.log(todaysMeals.breakfast) // "Maggi"
console.log(todaysMeals.lunch.roti) // "Butter Naan"

In the first one, we simply put a dot on the object to access its properties.

The second one has a nested object inside of an object so we first select the object we want todaysMeals.lunch and then the key we want inside of that object with another dot todaysMeals.lunch.roti. Dot Notation targets specific existing variables.

  1. Square Bracket Notation

Even in Bracket Notation, we can access properties similarly. We use square brackets [ ] and wrap them around the key string in quotation marks " ". (The quotes are essential!). Bracket notations can have dynamic values as we will see ahead.

console.log(todaysMeals["breakfast"]) // "Maggi"
console.log(todaysMeals["lunch"]["roti"]) // "Butter Naan"

Let's create keys in an empty object

const games = {}

games.outdoorGame = "football" // With dot notation
console.log(games) // { outdoorGame: "football"}

games['indoorGame'] = "chess" // With bracket notation
console.log(games) // { outdoorGame: "football", indoorGame: "chess"}

So what's the difference except for the syntax?

Accessing keys with dot notation has limitations! Suppose I have this object:

const object = {
1 : "Cat", 
2 : "Dog"
}
// When we try
console.log(object.1) // Uncaught SyntaxError: missing ) after argument list
console.log(object[1]) // Cat

Why is this? This is because we cannot use dot notation to access a number directly, it is an invalid syntax but we can do so with bracket notation.

Square Bracket Notations also have other amazing superpowers as compared to dot notation

const fruit = "apples"  // External Variable
const fruitsSeller = {
  "apples" : "2kg", // the key name is same as the value of external variable
  "mangoes" : "5kg", 
  "oranges" : "1kg", 
}  
console.log(fruitsSeller[fruit]) // 2kg
console.log(fruitsSeller.fruit) // undefined

We were trying to access the key "apples" inside the object fruitsSeller through an external variable fruit.

1. When we try this with dot notation JS goes to look for the fruit key in the object fruitsSeller and does not find it so gives us undefined.

2. Whereas when we try to use bracket notation JS recognizes the fact that we are trying to access the value of an external variable as the key name in the object fruitsSeller. (Also notice how here we haven't used quotations to access fruits because we are passing in a variable: ❌fruitsSeller["fruit"] ❌ .)

Dynamic Fields

Dynamism means to change something.

Dynamic Fields in JavaScript is the ability to create and modify properties of an object and other elements. This blog focuses on objects.

We can create and modify objects through both notations. But the difference is that dot notation can only modify existing properties and cannot use external variables.

Bracket notation can access values dynamically. We can use variables to access values inside the object with the bracket notation.

 const exampleObject = {
 name: "Jenna", 
 age: 25,
 country: "France"};

let propertyName = "name";
console.log(exampleObject[propertyName]) // Jenna

// Now suppose I change the propertyName
propertyName = "age";
console.log(exampleObject[propertyName]) // 25

So basically if the value of the variable exists as a key of the object ("name" and "age" are present in the object exampleObject) we can access the value of that key ("Jenna" and 25) and even change the property name (key) we want. We can dynamically access the keys. And by changing the value of the variable outside we can access different keys dynamically.

Say our program was changing the key with a for-loop or with a type of iteration we must use bracket notation.

// An example using reduce that recieves dynamic values
const clothesStorePrices = {
  dress: 1000,
  sportsShoes: 4000,
  shirt: 400,
  tShirt: 200
};

const ordersOnline = [
  { name: "Sania", clothes: ["dress", "tShirt", "sportsShoes"] },
  { name: "Jack", clothes: ["tShirt"] } // Jack is broke
];

const totalAmountEarned = ordersOnline.reduce(
  (totalAmount, currentOrder) =>
    currentOrder.clothes.reduce(
      (singleOrderAmount, currentItem) =>
        (singleOrderAmount += (clothesStorePrices[currentItem] ?? 0)),
      0
    ) + totalAmount,
  0
);
console.log(totalAmountEarned); // 5400

Here, if you notice we have --> calculated single order amount by replacing the key names of clothesStorePrices with the variable currentItem clothesStorePrices[currentItem]---> currentItem is changing values dynamically from the ordersOnline array ---> Then lastly we add the single order amounts to the total amount.

We can even create and modify a field at the same time too!

const basicColours = { 
colour1: "red",
colour2: "yellow",             
}

const myThirdColour = "colour3"
basicColours[myThirdColour] =  "blue"
console.log(basicColours) // const basicColours = {colour1: "red", colour2: "yellow", colour3: "blue"           }

ES6 syntax is the cherry on top. We can do this too:

let myThirdColour = "colour3"
const basicColours = { 
colour1: "red",
colour2: "yellow", 
[myThirdColour] : "blue"            
}
console.log(basicColours.colour3) // blue
const demoOfDynamicFields = (keyName, value) => ({ [keyName] : "animal"})
console.log(demoOfDynamicFields("dog")) // {dog: 'animal'}
console.log(demoOfDynamicFields("cat")) // {cat: 'animal'}
// We can modify the keyName as we want in a function
// And values ofcourse can be passed without any such syntax
const demoOfDynamicFields = (keyName, value) => ({ [keyName] : value})
console.log(demoOfDynamicFields("dog", "woof")) // {dog: 'woof'}
console.log(demoOfDynamicFields("cat", "meow")) //  {cat: 'meow'}

Use Cases

  • If you made a website and it has a SignUp form the keys and values can be modified, created and deleted dynamically depending on the user's input.

  • If you want to create dynamic templates with objects that the user can alter to his preferences. Like if a buyer wanted to filter the clothes he/she wants to buy on an online site, we can allow them to add their preferences for say, "blue t-shirt" and remove all the other colored t-shirts.

  • If say a user subscribes to your website you can provide them extra content and limit non-subscribers according to their authentication status.

  • In any type of iteration for-loops / reduce / others we use dynamic fields.

What should we use?

  • When we don't have to access anything dynamically it is easier to use dot notation. To create and modify a specific property we use dot notation.

  • When we want to access anything dynamically, we must use bracket notation. To create or modify a dynamic property we use bracket notation. In iterations, we use square bracket notation.

Thanks for reading! :)