close
The Wayback Machine - https://web.archive.org/web/20240930175838/https://www.geeksforgeeks.org/how-to-add-a-property-to-a-javascript-object-using-a-variable-as-the-name/
Open In App

How to add a property to a JavaScript object using a variable as the name?

Last Updated : 26 Jul, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In JavaScript, you can dynamically add a property to an object using a variable as the name. This allows you to create flexible and dynamic objects based on runtime values, enhancing code reusability and adaptability.

There are several methods that can be used to add a property to a JavaScript object using a variable as the name.

  • Using Dot Notation
  • using Object.assign()
  • Using ES6 Computed Property Names

Approach 1: Using Dot Notation

Using dot notation with square brackets, you can add a property to a JavaScript object using a variable as the name, making it accessible and modifiable directly through the object.

Example: in this example, Object object1 has properties firstname and lastname. We add a property named age with value 25 using dot notation.

Javascript




let object1 =
    { firstname: "Romy", lastname: "Kumari" };
 
// Step 1: Define the property name and value
const newPropertyName = 'age';
const newPropertyValue = 25;
 
// Step 2: Add the new property using dot notation
object1[newPropertyName] = newPropertyValue;
 
// Step 3: Access and
//display the updated object
console.log(object1);


Output

{ firstname: 'Romy', lastname: 'Kumari', age: 25 }

Approach 2: using Object.assign()

Using Object.assign(), the new object is created by merging existing object1 with new property { [newPropertyName]: newPropertyValue }. The original object remains unchanged.

Example:

Javascript




let object1 = { firstname: "Romy", lastname: "Kumari" };
 
// Step 1: Define the property name and value
const newPropertyName = 'age';
const newPropertyValue = 25;
 
// Step 2: Add the new property using Object.assign()
const updatedObject =
    Object.assign({}, object1,
        { [newPropertyName]: newPropertyValue });
 
// Step 3: Access and display the updated object
console.log(updatedObject);


Output

{ firstname: 'Romy', lastname: 'Kumari', age: 25 }

Approach 3: Using ES6 Computed Property Names:

ES6 introduces computed property names, which allows you to use variables to set property names directly when defining an object.

Example: in this example, A new object is created by spreading object1 properties and adding a property named ‘age’ with the value 25.

Javascript




const propertyName = 'age';
const propertyValue = 25;
 
const object1 =
    { firstname: "Romy", lastname: "Kumari" };
 
// Add the new property using ES6 Computed Property Names
const updatedObject = {
    ...object1,
    [propertyName]: propertyValue,
};
 
// Access and display the updated object
console.log(updatedObject);


Output

{ firstname: 'Romy', lastname: 'Kumari', age: 25 }


Previous Article
Next Article

Similar Reads

How Check if object value exists not add a new object to array using JavaScript ?
In this tutorial, we need to check whether an object exists within a JavaScript array of objects and if they are not present then we need to add a new object to the array. We can say, every variable is an object, in Javascript. For example, if we have an array of objects like the following. obj = { id: 1, name: ''Geeks1" }, { id: 2, name: '"Geeks2"
3 min read
How to create a variable using a user-defined name in JavaScript ?
In this article, we will learn to create a variable using the user-defined name in JavaScript. Variables in JavaScript: Basically, it is a container that holds reusable data in JavaScript. The variable's value can be changed during program execution and should be declared before using it. Before ES6 declares a variable, we just use the var keyword
2 min read
variable === undefined vs. typeof variable === “undefined” in JavaScript
Undefined comes into the picture when any variable is defined already but not has been assigned any value. Undefined is not a keyword. A function can also be undefined when it doesn't have the value returned. There are two ways to determine if a variable is not defined, Value and type. var geeks; alert ( geeks === undefined) It's so clear that you
2 min read
How to declare object with computed property name in JavaScript ?
In this article, we learn how to declare an object with a computed property name. Before beginning this article, we have to know about the javascript objects. Computed Property Names: The ES6 computed property names feature allows us to compute an expression as a property name on an object. Javascript Object: Javascript objects contain key-value pa
2 min read
How to Add Duplicate Object Key with Different Value to Another Object in an Array in JavaScript ?
Adding duplicate object keys with different values to another object in an array in JavaScript refers to aggregating values under the same key from multiple objects in an array, creating a new object where each key corresponds to an array of associated values. Table of Content Using for...of LoopUsing reduce()Using a Map for Multiple ValuesUsing fo
4 min read
JavaScript SyntaxError - Missing variable name
This JavaScript exception missing variable name occurs frequently If the name is missing or the comma is wrongly placed. There may be a typing mistake. Message: SyntaxError: missing variable name (Firefox)SyntaxError: Unexpected token = (Chrome)Error Type: SyntaxErrorCause of Error: There might be a variable missing a name. This is because of synta
2 min read
How to Convert String to Variable Name in JavaScript?
In JavaScript, if we consider the variable names as string values, it is difficult to transform a variable’s name into a string. However, this problem has been handled in many ways for example, static properties of objects, eval(), and modern ways such as Map can be used to achieve the essential effect of dynamic variable creation, such methods are
3 min read
How to Find Property by Name in a Deep Object Using Lodash?
When working with deeply nested objects in JavaScript, finding a specific property can be challenging. Using Lodash, a powerful utility library, simplifies this task with its robust set of functions. This guide explores how to effectively search for a property by name within a deeply nested object using Lodash, ensuring you can quickly and efficien
2 min read
How to compare two objects to determine the first object contains equivalent property values to the second object in JavaScript ?
In this article, we are going to learn about comparing two objects to determine if the first object contains equivalent property values to the second object, In JavaScript, comparing the values of two objects involves checking if they have the same properties with corresponding values. Given two objects obj1 and obj2 and the task are to check that
6 min read
HTML | DOM Object name Property
The HTML | DOM Object name Property is used to set or return the value of a name attribute of an <object> element. The name attribute is used to specify the name of the embedded file. Syntax: It returns the name property objObject.nameIt is used to set the name property. objObject.name = name Property Values: It contains the value i.e name wh
2 min read
JavaScript Set object key by variable
In order to set an object's key by variable, here are few steps to follow. Steps: First make a variable.Then make a object.Assign that variable a value. Example-1: This example sets the object key by variable key and then inserts {"GFG_key":"GFG_Val"} object to a array. C/C++ Code <h1 style="color:green;"> GeeksForGeeks </h1>
2 min read
How to use a variable for a key in a JavaScript object literal?
In ES5 and earlier, you could not use a variable as a property name inside an object literal. The only option you had was to create the object literal, assign the variable property name with value and pass the resulting object to the animate method. ES6 defines 'ComputedPropertyName' as part of the grammar for object literals, which helps use a var
1 min read
How to check the type of a variable or object in JavaScript ?
In this article, How to Check the Type of a Variable or Object in JavaScript? In JavaScript, the typeof operator is used to determine the typeof an object or variable. JavaScript, on the other hand, is a dynamically typed (or weakly typed) language. This indicates that a variable can have any type of value. The type of the value assigned to a varia
2 min read
How to get a variable name as a string in PHP?
Use variable name as a string to get the variable name. There are many ways to solve this problem some of them are discussed below: Table of Content Using $GLOBALSUsing $$ OperatorUsing debug_backtrace()Using get_defined_vars() and array_search()Method 1: Using $GLOBALS: It is used to reference all variables available in the global scope. It is an
3 min read
How to get the Class Name of an Object in JavaScript
In this article, we will learn how we can get the class Name of an Object with multiple approaches in JavaScript. In JavaScript, determining an object's class name can be done using multiple approaches. The constructor property of an object reveals the function that created it, while the instanceof operator checks if an object is an instance of a c
3 min read
How to parse HTTP Cookie header and return an object of all cookie name-value pairs in JavaScript ?
To parse HTTP Cookie header we will spilt the cookies data and create objects from the key-value extracted from cookies. Cookies are simply small text files that a web server sends to the user's browser. They contain the following data. Name-value pair with actual data.The expiry date for when the cookie becomes invalid.Domain and path of the serve
3 min read
How to Merge Child Object Value to Parent Key Based on Key Name in JavaScript ?
JavaScript allows us to merge values from child objects into their parent object based on a specific key name. This can be useful for organizing data or simplifying complex structures. There are several approaches available in JavaScript to merge child object values to parent key based on the key name which are as follows. Table of Content Using fo
4 min read
How to get the first key name of a JavaScript object ?
In JavaScript, accessing the first key name of an object involves identifying the initial property defined within that object. This concept is useful when you need to interact with or manipulate object properties in a specific order, particularly when the sequence of properties is relevant. Here we have some common approaches to get the first key n
2 min read
How to Name and Retrieve a Git Stash by Name?
Git stash is a powerful feature that allows developers to temporarily save changes in their working directory and staging area that they don't want to commit immediately. By naming stashes, you can organize and retrieve them more easily. Here's a detailed guide on how to name and retrieve a Git stash by name. Table of Content Stashing Changes with
3 min read
How to Name a Stash and Retrieve a Stash by Name in Git?
Git is an important tool for developers, enabling efficient version control and collaboration on projects. One powerful feature of Git is the ability to stash changes, temporarily storing modifications without committing them. This is particularly useful when you need to switch contexts or branches but aren’t ready to commit to your current work. T
3 min read
How to access an object having spaces in the object's key using JavaScript ?
Given an object and the task is to access the object in which the key contains spaces. There are a few methods to solve this problem which are discussed below: Approach 1: Create an object having space-separated keys.Use square bracket notation instead of dot notation to access the property. Example: This example implements the above approach. C/C+
2 min read
How to get the object's name using jQuery ?
In this article, we will learn how to find the name of an element using jQuery. The name attribute can be applied to multiple elements in HTML and is used to specify a name for any element. The name attribute of any element can be found out using the attr() method. This method is used to find the value of any attribute of the first element in the m
2 min read
How to use array that include and check an object against a property of an object ?
Array.includes() Method: In JavaScript, includes() method is used to determine that a particular element is present in an array or not. It returns true if the element is present and false when it is absent. Syntax: array_name.includes(searchElement, ?fromIndex) Parameters: searchElement: The element to be search in the array.fromIndex: The index fr
3 min read
How to Replace an Object in an Array with Another Object Based on Property ?
In JavaScript, replacing an object in an array with another object based on a specific property involves identifying and updating elements within the array. This task is essential when modifications to individual objects are required, such as updating values or swapping objects based on a particular property criteria. Table of Content Using map()Us
3 min read
How to Replace an Object in an Array with Another Object Based on Property ?
In JavaScript, an array is a data structure that can hold a collection of values, which can be of any data type, including numbers, strings, and objects. When an array contains objects, it is called an array of objects. Table of Content Using findIndex and splice methodsUsing filter and concat methodsUsing the map methodUsing findIndex and splice m
3 min read
How to conditionally add a member to an object using JavaScript?
Objects are the most important data types and are building blocks for modern JavaScript. They are different from primitive data-types such as String, Number, Boolean, null, etc. But we can make these datatypes as objects by using the new keyword. Below are the approaches to conditionally adding a member to an object which are as follows: Table of C
3 min read
How to Add an Element to a JSON Object using JavaScript?
In JavaScript to add an element to a JSON object by simply assigning a value to a new key. We can use the approaches mentioned below. Let's first create a JSON object in JavaScript and then implement the possible approaches. let jsonObject = { key1: 'value1', key2: 'value2' };Table of Content Using Dot Notation to add an element to a JSON objectUsi
3 min read
HTML| DOM Variable Object
The DOM Variable Object is used to represent HTML <var> element. The var element is accessed by getElementById(). Syntax: var element = document.getElementById("ID"); Where “id” is the ID assigned to the “var” tag. Example-1: C/C++ Code &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;HTML| DOM Vari
2 min read
How to Check if a Variable is a MomentJS Object?
Variables are used to hold different types of data in JavaScript. Sometimes, we see a variable and we don't know if it is a Moment.js object or just a regular object or string. Knowing how to identify a Moment.js object can be really helpful in these situations. This is important because Moment.js objects have special methods and properties that ar
2 min read
How to check a JavaScript Object is a DOM Object ?
Prerequisite: DOM (Document object model), Instanceof Operator DOM (Document Object Model): Document Object Model is a hierarchical representation of HTML and XML documents in a format that is easier to interpret in terms of programming. It makes manipulation of tags, elements, attributes, and classes by interpreting its structure in the form of a
2 min read