Adding property to javascript object

Add Property to an Object in Javascript (6 ways)

This article demonstrates easy ways to add a property in the javascript object using different methods and various example illustrations. We will also see how to add new properties dynamically to javascript objects after their creation.

Table of Contents:

Add Property to Javascript Object Dynamically using Object.defineProperty()

Javascript’s Object.defineProperty() method is static and adds a new property to an object directly or modifies an existing property. This method returns the modified Object.

Add the property to an object

Frequently Asked:

// create a new function definePropertyDynamically var definePropertyDynamically = function ( _object, _propertyName, _propertyValue )< var config = < value: _propertyValue, writable: true, enumerable: true, configurable: true >; Object.defineProperty( _object, _propertyName, config ); >; let personObject = < personFirstName: 'George', personLastName: 'Smith', dateOfBirth: "Nov 14 1984">; //use this method to add properties to any object definePropertyDynamically( personObject, "city", "Santiago" ); // print the modified object console.log(personObject);

Explanation:-

  • Here, in the above code we are creating a function that will be able to add a property to any object.
  • _object -> name of the object for which we need to add a new property
  • _propertyName -> is the name of the property
  • _propertyValue -> value to be assigned to the property.
  • Within the function the code makes this new property writable, enumerable and configurable and hence can be added dynamically after the object creation.

Add Property to Javascript Object

Add the property to an object

//original object let personObject = < personFirstName: 'George', personLastName: 'Smith', dateOfBirth: "Nov 14 1984">; // new property with it's value personObject["city"] = "Santiago"; // object after adding new property console.log(personObject)

Add Property to Javascript Object using eval()

Javascript’s eval(string) function is used to evaluate the javascript code represented as a string. It evaluates the expression passed in the function as a parameter.

Add the property to an object

//original object let personObject = < personFirstName: 'George', personLastName: 'Smith', dateOfBirth: "Nov 14 1984">; // new property with it's value let propertyName = "city"; let propertyValue = "Santiago"; //eval() to evaluate the expression eval("personObject." + propertyName + " = '" + propertyValue + "'"); // object after adding new property console.log(personObject)

Note that eval() has some security concerns, and therefore, if you are planning to use it for the values supplied by the user, then, in that case, avoid using this function.

Add Property to Javascript Object using Spread Operator

Javascript’s Spread syntax(…) allows an iterable to be expanded in places where zero or more arguments or elements are expected.

Add the property to an object

//original object let personObject = < personFirstName: 'George', personLastName: 'Smith', dateOfBirth: "Nov 14 1984">; // new property with it's value let propertyName = "city"; let propertyValue = "Santiago"; //Spread syntax(. ) to add a new property personObject = < . personObject, propertyName: propertyValue>// object after adding new property console.log(personObject)

Add Property to Javascript Object using Comma Operator

Add the property to an object

// create a new object and assign it to a variable personObject let personObject = < personFirstName: 'George', personLastName: 'Smith', dateOfBirth: "Nov 14 1984">; // new property with it's value let propertyName = "city"; let propertyValue = "Santiago"; //use comma operator to add a new property to the same personObject personObject = (personObject, personObject[propertyName] = propertyValue, personObject); // object after adding new property console.log(personObject);

Add Property to Javascript Object using map()

Javascript’s map() method is used to create a new array with the elements resulting from applying the provided function on the calling array elements.

Add the property to an object

// create a new object and assign it to a variable personObject let personObject = < personFirstName: 'George', personLastName: 'Smith', dateOfBirth: "Nov 14 1984">; // new property with it's value let propertyName = "city"; let propertyValue = "Santiago"; //use map() method to add a new property to the personObject [personObject].map( (obj) => obj[propertyName] = propertyValue ); // object after adding new property console.log(personObject);

I hope this method helped you to add a new property to an existing javascript object. Good Luck.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

JavaScript Object Properties

Properties are the most important part of any JavaScript object.

JavaScript Properties

Properties are the values associated with a JavaScript object.

A JavaScript object is a collection of unordered properties.

Properties can usually be changed, added, and deleted, but some are read only.

Accessing JavaScript Properties

The syntax for accessing the property of an object is:

The expression must evaluate to a property name.

Example 1

Example 2

JavaScript for. in Loop

The JavaScript for. in statement loops through the properties of an object.

Syntax

The block of code inside of the for. in loop will be executed once for each property.

Looping through the properties of an object:

Example

const person = <
fname:» John»,
lname:» Doe»,
age: 25
>;

for (let x in person) txt += person[x];
>

Adding New Properties

You can add new properties to an existing object by simply giving it a value.

Assume that the person object already exists — you can then give it new properties:

Example

Deleting Properties

The delete keyword deletes a property from an object:

Example

const person = <
firstName: «John»,
lastName: «Doe»,
age: 50,
eyeColor: «blue»
>;

Example

const person = <
firstName: «John»,
lastName: «Doe»,
age: 50,
eyeColor: «blue»
>;

The delete keyword deletes both the value of the property and the property itself.

After deletion, the property cannot be used before it is added back again.

The delete operator is designed to be used on object properties. It has no effect on variables or functions.

The delete operator should not be used on predefined JavaScript object properties. It can crash your application.

Nested Objects

Values in an object can be another object:

Example

You can access nested objects using the dot notation or the bracket notation:

Example

Example

Example

Example

Nested Arrays and Objects

Values in objects can be arrays, and values in arrays can be objects:

Example

To access arrays inside arrays, use a for-in loop for each array:

Example

for (let i in myObj.cars) <
x += «

» + myObj.cars[i].name + «

«;
for (let j in myObj.cars[i].models) <
x += myObj.cars[i].models[j];
>
>

Property Attributes

All properties have a name. In addition they also have a value.

The value is one of the property’s attributes.

Other attributes are: enumerable, configurable, and writable.

These attributes define how the property can be accessed (is it readable?, is it writable?)

In JavaScript, all attributes can be read, but only the value attribute can be changed (and only if the property is writable).

( ECMAScript 5 has methods for both getting and setting all property attributes)

Prototype Properties

JavaScript objects inherit the properties of their prototype.

The delete keyword does not delete inherited properties, but if you delete a prototype property, it will affect all objects inherited from the prototype.

Источник

Читайте также:  Facebook sharer php src
Оцените статью