Is it possible to assign a property name using a string during the creation of an object?

Can an object property be named directly within the object declaration instead of afterwards?

For example, this syntax works:

var name  = "foo";
var obj   = {};
obj[name] = "bar"; // obj.foo === "bar"

But is there a way to define it inside the object itself, like this:

var name  = "foo";
var obj   = {
    name: "bar" // obj.name === "bar"
};

I am aware that strings can be used for property names, so I attempted a workaround, but it failed:

var obj   = {
    "" + name: "bar"
};

Is there a method to accomplish this task?

Answer №1

In ES2015, and not in ES5, there is no way to achieve this.

let key = "name";
let obj = {
  [key]: "value"
};

console.log(obj)

From ECMAScript 2015 onwards, you can now use computed property names when initializing objects. This means you can use an expression within brackets [] to dynamically set the property name. It mirrors the bracket notation used for accessing properties, but now you can utilize it during object creation as well.

Learn more about computed properties in object initializers on MDN

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to execute "green arrow" unit tests directly with Mocha in IntelliJ IDEA, even when Karma and Mocha are both installed?

My unit tests are set up using Karma and Mocha. The reason I use Karma is because some of the functionality being tested requires a web browser, even if it's just a fake headless one. However, most of my code can be run in either a browser or Node.js. ...

I am experiencing issues with local storage getItem() function not functioning properly within NUXT JS

Currently working on creating a shopping cart using nuxt js. Successfully able to store the cart data in local storage, but facing difficulty in retrieving the data. Refer to the screenshots for more details: https://i.sstatic.net/X7dL9.png https://i.sstat ...

#Error 500 encountered in a basic Ruby on Rails and AngularJS collaboration

Thanks to everyone for taking the time to assist me with this problem. As a newcomer to Ruby, the solution may be quite simple. I have developed an API that facilitates communication between Ruby and Angularjs. Here is the API: class EntriesController < ...

Using dynamic values in Angular functions

Here is the code snippet I am working with: $scope.testByValue = function() { $scope.fChanged($scope.lists.title); }; But I am facing an issue on the page where the value for: $scope.testValue = testValue; The variable testValue is being assigned a ...

Guide on accessing the fastify application instance within an imported module

Currently, I am working on developing a rest API using Fastify and I am in the process of organizing my code into separate files for better structure. One issue I am facing is how to access the Fastify instance within a file that I import. The following s ...

Is it possible to simultaneously verify if an array is empty within an Object along with checking the other fields?

Let's say I have an object that has the following structure: filter: { masterName: '', service:[], } What is the best way to determine if both the array and masterName field are empty? ...

Having trouble importing the "@angular/material" module

I'm completely new to working with the MEAN stack and currently running into issues with Angular's material module. I am attempting to bring in the "@angular/material" module into my code, but encountering an error each time I try to import it. T ...

unable to retrieve the chosen item from the dropdown menu

How can I retrieve the value of the selected item from a dropdown menu without getting an undefined error? You can find my code on Jsfiddle. Can anyone spot what might be causing this issue? <select class="ddl_status" id="status_ddl_20" style="display ...

Is there a way to load and play different sounds on multiple audio players based on the length of an array?

I am attempting to load various sounds (.mp3 audio) on separate audio players that are displayed on a single HTML page. The number of players displayed on the screen is determined by the length of the array. In this specific example, I have 3 elements in t ...

Tips on making an array readable by JavaScript using Jinja2 and Google App Engine

I'm currently facing an issue with transferring an array from a server to a web page through Jinja2 in Google App Engine. Despite my efforts, I'm struggling to make the array readable by my jQuery code. This is all new to me as it's my first ...

Creating components in reactjs using the render function

Just a quick query – I've been diving into react js recently. Typically, when we create a component in React, we include the HTML template within the render function. I've noticed that most examples consist of small components with minimal HTM ...

Can a before hook ever run after a test in any situation, Mocha?

My before hook runs after the initial test and at the conclusion of the second test. Here is the code for my before hook: before(function () { insightFacade.addDataset("courses", content) .then(function (result: InsightResponse) { ...

Utilize a dynamic URL within the HTML audio element

Currently, I am working with the use of the audio tag in HTML and AngularJS. I need to specify the source of the audio file I want to play, as shown below. <audio src="http://localhost/audio/221122/play/212223.mp3" audio player controls p ...

Exploring the World of Dynamic Table ID Access in Rails 5 with Coffeescript

Within my Index view, I have a table that I want to dynamically populate with an ID. This is what I've attempted so far: id="table_<%= @controller_name %>" The method in my controller looks like this: def get_controller_name @controller_nam ...

What is the best way to determine if an object.property is defined in Angular 2?

Is there a similar function in Angular 2 to angular.isDefined from Angular 1? I have tried using the safe navigation operator ?., which is only supported in templates. ...

Simple steps for transforming an array into a JavaScript object

Here is an array resembling a JSON structure with n elements: const mainData = [ { phrase: "Phrase 1", categorynumber: 1, optionnumber: 1, }, { phrase: "Phrase 2", categorynumber: 1, optionnumber: 2, }, ...

What is the best way to adjust the width of floating divs to completely fill the space they occupy?

On the first picture, there are six equal divs displayed. As the screen size increases, the width of the divs also grows to fill up their space, like a table cell or another div. If there is enough space in the first row to accommodate the fourth div, it s ...

Creating dynamic web content using PHP and JavaScript

I stumbled upon a tutorial on the PHP.net website within the "PHP and HTML" manual which includes an example titled Generating JavaScript with PHP. Currently, I am experimenting with a basic demo of this concept on my own to grasp the process before attem ...

Tips for adjusting the color of the white tick in Material UI Checkbox with React and JavaScript

I'm currently attempting to customize the default white tick (not the checkbox background!) and change it to a different color that I choose. While I have come across solutions for earlier versions of MUI and React, I am specifically looking for a sol ...

Express displays HTML code as plain text

I am currently facing an issue where I am trying to display an html table on /guestbook.ejs and then redirect it to /guestbook. However, the content of my guestbook.ejs file is being displayed as plain text rather than rendering the HTML code. Below is th ...