- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to add a property to a JavaScript object using a variable as the name?
In this article, you will understand how to add a property to a JavaScript object using a variable as the name. Adding property to an object can be achieved by two methods. The first is the dot (.) notation and the second is using the brackets([]).
Example 1
In this example, let’s use the dot (.) notation.
var inputObject = {a: "value1"}; console.log("An object is created with properties: ", inputObject) inputObject.b = "value2"; console.log("
After adding properties, the object now contains: ", inputObject) console.log(inputObject)
Explanation
Step 1 − Define an object namely inputObject.
Step 2 − Add an additional property to the object using dot notation.
Step 3 − Display the values.
Example 2
In this example,
var inputObject = {a: "value1"}; console.log("An object is created with properties: ", inputObject) inputObject['c'] = "value3" console.log("
After adding properties, the object now contains: ", inputObject) console.log(inputObject)
Explanation
Step 1 − Define an object namely inputObject.
Step 2 − Add an additional property to the object using bracket notation.
Step 3 − Display the values.
Advertisements