Javascript add property to all objects

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 add property to all objects

Last updated: Dec 22, 2022
Reading time · 5 min

banner

# Table of Contents

# Add a Key/Value pair to all Objects in Array in JavaScript

To add a key/value pair to all objects in an array:

  1. Use the Array.forEach() method to iterate over the array.
  2. Use dot notation to add a key/value pair to each object.
  3. The key/value pair will get added to all objects in the array.
Copied!
const arr = [id: 1>, id: 2>]; arr.forEach(object => object.color = 'red'; >); // 👇️ [, ] console.log(arr);

The function we passed to the Array.forEach method gets called with each element (object) in the array.

If the name of the key you need to add to the object contains hyphens, spaces or starts with a number, use bracket notation to add the key to each object.

Copied!
const arr = [id: 1>, id: 2>]; arr.forEach(object => object['full name'] = 'Bobby Hadz'; >); // [ // < id: 1, 'full name': 'Bobby Hadz' >, // // ] console.log(arr);

The Array.forEach() method iterates over the array and adds the key-value pair to each object in place.

If you’d rather not mutate the original array, use the Array.map() method.

# Add a Key/Value pair to all Objects in Array using Array.map()

This is a three-step process:

  1. Use the Array.map() method to iterate over the array.
  2. Use the spread syntax to add a key/value pair to each object.
  3. The key/value pair will get added to all objects in the new array.
Copied!
const arr = [id: 1>, id: 2>]; const arrWithColor = arr.map(object => return . object, color: 'red'>; >); // 👇️ [, ] console.log(arrWithColor); // 👇️ [, ] console.log(arr);

The function we passed to the Array.map() method gets called with each element (object) in the array.

We used the spread syntax (. ) to unpack the key/value pairs of each object and added an additional key/value pair.

Copied!
const arrWithColor = arr.map(object => return . object, color: 'red'>; >);

An easy way to think about the spread syntax is that we are unpacking the key/value pairs of a source object into a target object.

We basically transfer over the id property and add a color property to each object.

The Array.map() method is different than Array.forEach() because map() returns a new array, whereas forEach() returns undefined .

When using the forEach() method, we mutate the array in place.

# Using Object.assign() instead of the spread syntax (. )

You can also use the Object.assign() method instead of using the spread syntax.

Copied!
const arr = [id: 1>, id: 2>]; const arrWithColor = arr.map(object => return Object.assign(object, color: 'red', country: 'Chile'>); >); // [ // < id: 1, color: 'red', country: 'Chile' >, // // ] console.log(arrWithColor);

We used the Object.assign() method to copy the key-value pairs of one or more objects into a target object.

The arguments we passed to the Object.assign method are:

  1. the target object — the object to which the provided properties will be applied.
  2. the source object(s) — one or more objects that contain the properties we want to apply to the target object.

You can imagine that the key-value pairs of the object we passed as the second argument to Object.assign() , get copied into the object we supplied for the first argument.

# Conditionally adding a key-value pair to all objects in an array

If you need to conditionally add a key-value pair to all objects in an array, use the ternary operator.

Copied!
const arr = [id: 1>, id: 2>]; const arrWithColor = arr.map(object => return . object, name: object.id > 1 ? 'Bobby' : 'Alice'>; >); // 👇️ [ < id: 1, name: 'Alice' >, < id: 2, name: 'Bobby' >] console.log(arrWithColor);

The ternary operator is very similar to an if/else statement.

If the expression to the left of the question mark returns a truthy value, the operator returns the value to the left of the colon, otherwise, the value to the right of the colon is returned.

In the example, we check if the current object’s id property is greater than 1 .

If the condition is met, the string Bobby is returned for the name property, otherwise, the string Alice is returned.

Here is the equivalent if/else statement.

Copied!
const arr = [id: 1>, id: 2>]; const arrWithColor = arr.map(object => if (object.id > 1) return . object, name: 'Bobby'>; > else return . object, name: 'Alice'>; > >); // 👇️ [ < id: 1, name: 'Alice' >, < id: 2, name: 'Bobby' >] console.log(arrWithColor);

If the object’s id property is greater than 1 , the if block runs, otherwise, the else block runs.

# Add a Key/Value pair to all Objects in an Array using for. of

You can also use a simple for. of loop to add a key-value pair to all objects in an array.

Copied!
const arr = [id: 1>, id: 2>]; for (const obj of arr) obj.color = 'red'; > // 👇️ [ < id: 1, color: 'red' >, < id: 2, color: 'red' >] console.log(arr);

The for. of statement is used to loop over iterable objects like arrays, strings, Map , Set and NodeList objects and generators .

On each iteration, we add a new key-value pair to the current object, in place.

# Add a Key/Value pair to all Objects in an Array using a for loop

You can also use a basic for loop to add a key-value pair to all objects in an array.

Copied!
const arr = [id: 1>, id: 2>]; for (let index = 0; index arr.length; index++) arr[index].color = 'green'; > // 👇️ [ < id: 1, color: 'green' >, < id: 2, color: 'green' >] console.log(arr);

The basic for loop is quite verbose in comparison to forEach() or for. of .

We also have to use the index to access the object of the current iteration before adding a key-value pair.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Читайте также:  Css selector div with child
Оцените статью