Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptHow to get dynamic access to an object property in JavaScript ?

How to get dynamic access to an object property in JavaScript ?

In JavaScript, an object is a collection of properties, where each property consists of a key-value pair. Objects are a fundamental data type in JavaScript. You can create an object in JavaScript in the following ways:

  • By using the object literal notation, which is a comma-separated list of key-value pairs enclosed in curly braces
  • By defining the new keyword
  • By declaring the object constructor, & then creating objects of the constructed type
  • By using the Object.create() method

You can use a square bracket[] or dot notation(.) to get access or modify an object property. We will explore both ways to get access to the object property & will understand its basic implementation with the help of examples.

Syntax: This syntax describes the object creation:

const obj = {

    // Property name may be an identifier
    property1: value1,

    // Or a number
    property2: value2,
    ...
    "property n": value3, // Or a string
};

 

Example 1: This example describes the basic Object creation & displays their values in the console. Here, In the first two lines, we use dot notation to access the value of the name and course property. In the third line, we use bracket notation to access the value of the age property. In the fourth and fifth lines, we use dot notation and bracket notation to access the city and zipCode properties of the address object, respectively.

Javascript




const person = {
    name: 'John',
    course: 'GeeksForGeeks',
    'age': 30,
    address: {
        street: '123 Main St',
        city: 'New York',
        state: 'NY',
        zipCode: '10001'
    }
};
  
console.log(person.name); 
console.log(person.course);
console.log(person['age']); 
console.log(person.address.city); 
console.log(person['address']['zipCode']);


Output

John
GeeksForGeeks
30
New York
10001

You can access the properties of an object using dot notation or bracket notation(dynamic approach). There are 4 different techniques to get dynamic access to an object property:

Defining the Object Property name with the help of a string or variable: The square bracket syntax allows you to access or modify the properties of an object using a string or a variable. Here’s an example:

Example 2: In the example, we use the square bracket syntax to set the value of the foo property to ‘GeeksForGeeks‘.

Javascript




const myObj = {
    foo: 'Hello',
    bar: 'World'
};
  
const prop = 'foo';
myObj[prop] = 'GeeksForGeeks';
console.log(myObj.foo);


Output

GeeksForGeeks

Note that you can use any string or variable as the property name when using the square bracket syntax to access or set properties. However, if the property name contains special characters or spaces, you must enclose it in quotes. 

Example 3: This example describes getting the object’s property when the property name contains special characters or spaces.

Javascript




const myObj = {
    'my property': 'Hello',
    'another-property': 'World'
};
  
console.log(myObj['my property']);
console.log(myObj['another-property']);


Output

Hello
World

Implementing the square bracket notation: In JavaScript, you can implement the square bracket syntax to access the properties of an object.

Example 4: In the example, we first create an object myObj with two properties prop1 and prop2. We then create a variable propName and set it to ‘prop1’. Finally, we access the value of the prop1 property using the square bracket syntax myObj[propName].

Javascript




const myObj = {
    prop1: 'Hello',
    prop2: 'World'
};
  
const propName = 'prop1';
console.log(myObj[propName]);


Output

Hello

Accessing the nested object properties using square bracket notation: In JavaScript, you can access nested object properties using bracket notation. Bracket notation allows you to access the properties of an object using a string or a variable. When accessing nested properties, you can chain the bracket notation to access the nested properties.

Example 5: This example describes accessing the nested object properties with the help of square bracket notation.

Javascript




const myObj = {
    foo: 'Hello',
    bar: {
        baz: 'World'
    }
};
console.log(myObj['bar']['baz']);


Output

World

You can also use dot notation to access nested properties, but if the property name contains a special character or a space, you must use bracket notation. If you want to use a variable to access a nested property, you can chain the bracket notation with the variable.

Example 6: In this example, we use the variables prop1 and prop2 to access the baz property of the bar object.

Javascript




const myObj = {
    foo: 'Hello',
    bar: {
        baz: 'World'
    }
};
  
const prop1 = 'bar';
const prop2 = 'baz';
console.log(myObj[prop1][prop2]);


Output:

World

Note that when accessing nested object properties using bracket notation, you should ensure that each property in the chain exists. If any property in the chain is undefined, you will get an error.

Implementing the object destructuring to access object properties:

Using dot notation: In JavaScript, you can use object destructuring to access the properties of an object. Object destructuring allows you to extract the properties of an object and assign them to variables. Here’s an example of how you can use object destructuring in JavaScript:

Example 7: In the example, we first create an object myObj with two properties prop1 and prop2. We then use object destructuring to extract the prop1 and prop2 properties from the myObj object and assign them to variables with the same names. Finally, we log the values of the prop1 and prop2 variables.

Javascript




const myObj = {
    prop1: 'Hello',
    prop2: 'World'
};
  
// Using object destructuring to access properties
const { prop1, prop2 } = myObj;
console.log(prop1);
console.log(prop2);


Output:

Hello
World

You can also use object destructuring to assign properties to variables with different names.

Example 8: In the example above, we use object destructuring to extract the prop1 and prop2 properties from the myObj object and assign them to variables with different names greeting, and name. Finally, we log the values of the greeting and name variables.

Javascript




const myObj = {
    prop1: 'Hello',
    prop2: 'World'
};
  
// Using object destructuring to access 
// properties with different variable names
  
const { prop1: greeting, prop2: name } = myObj;
console.log(greeting); 
console.log(name);


Output

Hello
World

Note that when using object destructuring to access the properties of an object, the variable names must match the property names of the object. Otherwise, you can use the syntax propertyName: variableName to assign the property to a variable with a different name. If the property is not defined in the object, the variable will be assigned the value undefined.

Using bracket notation: In JavaScript, you can also use square bracket notation to destructure an object and access its properties. Square bracket notation is useful when you need to access an object property using a variable or when the property name is not a valid identifier.

Example 9: Here’s an example of how you can use square bracket notation to destructure an object:

Javascript




const myObj = {
    prop1: 'Hello',
    'prop-with-dash': 'Geeks'
};
  
// Using square bracket notation to access properties
const { prop1, 'prop-with-dash': prop2 } = myObj;
console.log(prop1); 
console.log(prop2);


Output

Hello
Geeks

In the example above, we first create an object myObj with two properties prop1 and ‘prop-with-dash’. Note that ‘prop-with-dash’ is not a valid identifier and cannot be accessed using dot notation. We then use square bracket notation to destructure the myObj object and assign its properties to variables prop1 and prop2. The property prop1 is assigned to the variable prop1 using dot notation, while the property ‘prop-with-dash’ is assigned to the variable prop2 using square bracket notation.

Example 10: You can also use square bracket notation to assign properties to variables with different names:

Javascript




const myObj = {
    prop1: 'Hello',
    'prop-with-dash': 'Geeks'
};
  
// Using square bracket notation to access 
// properties with different variable names
  
const { prop1: greeting, 'prop-with-dash': name } = myObj;
console.log(greeting);
console.log(name);


Output

Hello
Geeks

In the example above, we use square bracket notation to assign the property prop1 to the variable greeting and the property ‘prop-with-dash’ to the variable name. Note that the property name must be enclosed in quotes when using square bracket notation.

Using square bracket notation with object destructuring is useful when dealing with dynamic property names or properties with special characters that cannot be accessed using dot notation.

RELATED ARTICLES

Most Popular

Recent Comments