Javascript create object key

# How to Set Dynamic Property Keys with ES6 🎉

We can output the object value by passing in the appropriate key. Because I used emoji as the key in my example, it’s a bit tricky. So let’s look at a easier example.

let me =  name: 'samantha', >; // 1. Dot notation me.name; // samantha // 2. Bracket notation (string key) me['name']; // samantha // 3. Bracket notation (variable key) let key = 'name'; me[key]; // samantha 

# How to Access Object Value With Emoji Keys

Alright back to our emoji example. Let’s take a look at the output.

let cake = '🍰'; let pan =  [cake]: '🥞', >; // Output -> 

Unfortunately, when you’re using an Emoji as a key, you won’t be able to use the dot notation. You’re limited to the Bracket Notation.

// 2. Bracket notation (string key) pan['🍰']; // '🥞' // 3. Bracket notation (variable key) let key = '🍰'; me[key]; // '🥞' 

Источник

Javascript create object key

Dynamic JavaScript Object Keys

7 puppies with different colors

Photo by Jametlene Reskp on Unsplash

Excuse the barrage of doggos in the banner image. I searched for a stock image on unsplash for «Puppies with different colors being named by their mom». I do search in the tackiest of ways 😃

I hope they brighten your time also.

Recently, I found a ‘funny’ JS syntax when reviewing a pull request by Sigo, a colleague. I hadn’t used it previously. It looks like this:

const dataFromAPI = 'age'; let existingObject = name: 'John', [dataFromAPI]: 25 >; // Output

I looked up variables in object keys and decided to share it with you.

Keys and Values in Objects

In JavaScript, object keys and values are created in numerous ways either in object literals during initialization, or assignment using dot or bracket notation.

// Creating an object literal with keys and values let newObject = name: 'Jane', age: 24 >; // Adding a new key - bracket notation newObject["location"] = "Peru" // Adding a new key - Dot notation newObject.height = '1.95m' // Output

This is pretty much standard stuff. For values of keys, we are able to assign results from complex computation operations as a value. For keys, we can do something similar and even run the computation in the key.

A way to handle dynamic keys in objects prior to ES6 is to do something like:

let newObject = name: 'Jane', age: 24 >; const newData = "location"; newObject[newData] = "Nicaragua" // Output

A shorthand form introduced in ES6 using brackets lets us assign the variable in the object literal directly like this:

const newData = "location"; let newObject = name: 'Jane', age: 24, [newData]: "Nicaragua" >; // Output

While this shorthand form is proffering cleaner code, this scenario applies in multiple cases, where existing data (object) is augmented with data from a different source with a dynamic key.

Moving on to computed keys, the value of object keys can be computed directly in the object literal using the same bracket notation in the literal.

const newData = "lottery"; const didUserWin = true; let newObject = name: 'Doug', age: 42, [newData + (didUserWin ? 'Winner': 'Loser')]: "Assign any value or data here" >; // Output

This illustration also shows the use of conditions in the form of ternary operators.

This post is mainly to show the dynamism of both Object keys and values.

Let me know if you have any feedback using this.

Источник

Dynamic Object Key in JavaScript

An object is an entity that stores data in key-value pairs. In JavaScript, object keys and values can be created multiple ways, including assignment using dot or bracket notation or object literals during initialization. But sometimes an object key needs to be added dynamically.

This blog post will define the dynamic object key in JavaScript.

How to Set Dynamic Object Key in JavaScript?

In the ES6 version of JavaScript, developers can dynamically set the JavaScript property keys for their objects using the Bracket notation.

Follow the given syntax for setting a dynamic object key in JavaScript with bracket notation:

  • keyVar” is the variable name that stores the name of the key that will be added dynamically in the object.
  • keyName” is the name of a key that will be set dynamically in an object.

Example 1:

First, create a variable “newKey” for storing the name of the key “skill”:

Then, create an object “info”, with properties “name”, “age”, and “email”. Add another attribute of an object using the key “skill” that will dynamically add in an object:

Call the “console.log()” method by passing an object as an argument for printing all the properties of the object in a key-value pair:

The above output shows that the dynamic key “skill” is successfully added and accessed in an object:

Example 2:

Let’s print the value of the key “skill” stored in the “info” object:

The output indicates that the object “info” successfully accesses the value of the “newKey” variable and stores it as a dynamic key.

Conclusion

For adding an object key dynamically, use the bracket notation. First, store the key in a variable and then specify the variable name in bracket notation to set a key with value as a key-value pair in an object. This blog post defines the dynamic object key in JavaScript.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

How to create an object with dynamic keys in JavaScript

To create an object with dynamic keys in JavaScript, you can use ES6’s computed property names feature.

The computed property names feature allows us to assign an expression as the property name to an object within object literal notation.

const key = 'title'; const value = 'JavaScript'; const course =  [key]: value, price: '$99' >; console.log(course.title); // JavaScript console.log(course.price); // $99 

The value of the key can be any expression as long as it is wrapped in brackets [] :

const key = 'title'; const value = 'JavaScript'; const course =  [key + '2']: value, price: '$99' >; console.log(course.title2); // JavaScript console.log(course.price); // $99 

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Javascript create object key

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

banner

# Table of Contents

# Add a Key/Value pair to an Object in JavaScript

There are multiple ways to add a key/value pair to an object:

  • Use bracket [] notation, e.g. obj[‘name’] = ‘John’ .
  • Use dot . notation, e.g. obj.name = ‘John’ .
  • Use the Object.assign() method, passing it a target and source objects as arguments.

Here is an example of adding key-value pairs to an object using dot . and bracket [] notation.

Copied!
const obj = name: 'Bobby'>; // ✅ using dot notation obj.age = 30; // ✅ using bracket notation obj['country'] = 'Chile'; // 👇️ console.log(obj); // 👇️ Chile console.log(obj['country']); // 👇️ Bobby console.log(obj['name']);

# Using dot notation to add a key-value pair to an object

The first statement adds a key-value pair to the object using dot . notation. It is more concise and direct than using bracket [] notation.

Copied!
const obj = name: 'Bobby'>; obj.age = 30; obj.country = 'Chile'; obj.tasks = ['walk the dog', 'cook dinner']; // // name: 'Bobby', // age: 30, // country: 'Chile', // tasks: [ 'walk the dog', 'cook dinner' ] // > console.log(obj);

Источник

Читайте также:  Zaycev net index php
Оцените статью