5 Ways To Add A Property To Object in Javascript: Contact Mentor
5 Ways To Add A Property To Object in Javascript: Contact Mentor
1. “object.property_name” syntax
object.new_property = new_value
In the below example, we are creating an “id” property with the value 130 for
the employee object.
employee.id = 130
x
// update existing property
employee.age = 29
object.parent_prop.property = new_value
Below, the “country” property is added to a nested object which is the value of
the “location” parent property in the employee object.
employee.location = {}
employee.location.country = "USA"
object["property_name"] = property_value;
Square bracket syntax offers the following advantages over traditional dot x
operator:
In the below example, the “Last name” property cannot be directly added using
dot operator syntax due to the presence of space characters. Hence, we are able
to accomplish the creation of “Last name” property using square bracket syntax.
employee[custom_prop] = "Doe"
The nested objects are accessed using a series of multiple square bracket syntax
or alternatively, a combination of dot operator and square brackets can also be
used.
employee["location"] = {}
// Result: { name: "Jone Doe", age: 35, location: { zip code: 132
In the below example, we define “id” property for the employee object with a
value of 130 and writable as false. Hence, subsequent changes in the value of
the id property are discarded. Read more about Object.defineProperty from
developer.mozilla.org/Object/defineProperty .
Object.defineProperty(employee, 'id', {
value: 130,
writable: false
});
employee.id = 412;
The spread operator allows the creation of a soft copy of an object with existing
properties. The Spread operator followed by an inline property definition
allows the addition of new properties. Further, the properties of another object can
be added by using the spread operator multiple times.
In the below example, we create a copy of the employee object combined with
location and id properties. Next line, “id” object is added to employee object
using the spread operator.
Object.assign(target, source);
In the below example, we add the “id” property with value 670 to the employee
object using Object.assign.
x
Object.assign( employee, person);
Conclusion
Finally, to conclude the summary of the methods to add properties to objects is as
follows: