What is the best way to dynamically identify the property names of my object?

let weekData = [];
for (let i = 0; i < 7; i++) {
    const weekdayName = moment().subtract('days', i).format('dddd');
    weekData.push({
        [weekdayName]: 0
    });
}

I'm trying to create a list of objects with dynamic property names. The code above creates objects with properties named _name. How can I modify it to achieve this? I attempted using square brackets like this:

{ moment().subtract('days', i).format('dddd') : 0 }
, but encountered a syntax error. Can someone help me figure out the correct approach?

Answer №1

When it comes to assigning dynamic property names within an object literal, conventional methods won't cut it. However, fret not as bracket syntax comes to the rescue:

for (let i = 0; i < 7; i++){
    let dayName = moment().subtract('days',i).format('dddd');
    let dataObject = {};
    dataObject[dayName] = 0;
    weekData.push(dataObject);
}

Answer №2

To specify the key dynamically, it is important to use subscript notation.

for (var i = 0; i < 7; i++) {
    var _name = moment().subtract('days', i).format('dddd'), object = {};
    object [_name] = 0;
    week_count.push(object);
}

A shorter version of the code can be written like this

for (var i = 0; i < 7; i++) {
    var object = {};
    object[moment().subtract('days', i).format('dddd')] = 0;
    week_count.push(object);
}

If you prefer a one-liner solution, consider using Object.defineProperty , as shown below

for (var i = 0; i < 7; i++) {
    var _name = moment().subtract('days', i).format('dddd');
    week_count.push(Object.defineProperty({}, _name, {value:0,enumerable:true}));
}

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

Function not currently in operation

There seems to be an issue with the script not running or returning any answers. The console is blank. I am attempting to retrieve an answer from the Yandex Translate site (https://tech.yandex.com/translate/doc/dg/reference/translate-docpage/) Code: http: ...

Utilizing Google Sheets as a secure, read-only database for Angular applications without the need to make the sheet accessible to the

Seeking a way to utilize Google Sheets document as a read-only database for my Angular application, I have attempted various methods. However, the challenge with all these approaches is that they necessitate public sharing of the Sheet (accessible to anyon ...

Troubleshooting a Node.js server issue with a two-dimensional array

I am currently facing an issue with submitting a form that contains two-dimensional array fields on a post request in node.js. The problem lies in the fact that the server side is receiving a one-dimensional array with all the values combined. Below is an ...

Quicker way to apply appendChild

Is there a more efficient method to simplify the process of creating elements from an object fetched via a request? While the current code is functional, it seems overly verbose for what appears to be a straightforward task. async function getJobs() { ...

Retrieving every single .json file present in a specific folder

I'm working on developing an Android app that utilizes JSON data. Is there a method to establish a directory structure similar to this: http://......./jsons/*.json Or is there another way to append additional data into a JSON file (such as a.json) a ...

Can you provide guidance on achieving a gradient effect throughout the mesh, similar to the one shown in the example?

Check out my code snippet on JSFiddle: https://jsfiddle.net/gentleman_goat66/o5wn3bpf/215/ https://i.sstatic.net/r8Vxh.png I'm trying to achieve the appearance of the red/green box with the border style of the purple box. The purple box was created ...

Can someone explain the function of statements such as (function () { // code; }.call(this)); within a JavaScript module?

By utilizing the Function.prototype.call() method, it becomes possible to create a function that can be applied to various objects. I delved into the code of , which had been minified and required to be un-minified for examination. The structure of the co ...

Retrieve the size of the attribute of the initial array using a different array

I am working with two arrays array1 = [ {name: "samsung", views: 1200}, {name: "apple", views: 200} ] array2 = [ {name: "samsung-1234", views: 200}, {name: "apple-2332", views: 200}, {name: "samsung-6543", views: 400}, {name: "sam ...

How can we reset multiple selected values (mui chips) in a React Material-UI Autocomplete field when changing the value in a different field?

Is there a way to clear the mui-chips in Material UI Autocomplete TextField when the value in another field is changed? I have been struggling with clearing the subtype value when the Type value changes. Although I can update the drop-down options based on ...

Are multiple .then(..) clauses in Javascript promises better than just using one .then(..) clause?

In this particular scenario, I have set up a basic 'toy' node.js server that responds with the following JSON object: { "message" : "hello there" } This response is triggered by making a GET request to "http://localhost:3060/" So, it's reall ...

How to send a PHP variable to Ajax and execute a corresponding PHP function in response

I have a set of database records that are being displayed in separate div elements on the page. Each record corresponds to a specific ID, with its information displayed inside the div. My goal is to create a delete button for each record that would allow ...

Moving from the end to the beginning with a jQuery slider transition

Instead of relying on external plugins, I built this slider from scratch: function customSlider(selector, interval, index) { var slider = this; this.ind = index; this.selector = selector; this.slides = []; this.activeSlide = 0; this.amount; ...

selecting arrays within arrays according to their date values

With an array of 273 arrays, each containing data about a regular season NFL football game, I am looking to categorize the games by week. In total, there are 17 weeks in the NFL season that I want to represent using separate arrays. The format of my array ...

Open the HTML page from a separate directory

I'm facing an issue with loading additional HTML onto a page in my project when a link is clicked. The HTML fragment file I want to load is stored in a different folder within the project structure. Despite my efforts, I keep encountering a 404 error ...

Guide to integrating a Custom Font into live data on a PDF file with the help of jsPDF

I recently successfully converted a dynamic webpage to PDF using jsPDF and now I'm looking to customize the font family of the PDF document. Is there an option for this in jsPDF? Please advise, thank you! Here is my code snippet: <div id="#p ...

The results from various <div> elements are displayed based on the selection made from the dropdown menu

<body> <label for="country">Country : </label> <select id="country"> <option>Please select</option> <option name="CountryRevenue">Revenue</option> <option name="CountryQuantity">Quantity ...

Ensure that Google Tag Manager (GTM) delays the pageview until the SPA URL title is available

I'm dealing with a React SPA that manages all the URL titles on the frontend, so the historyChange event registered on GTM captures the visited URLs along with their titles correctly. However, I've noticed that on the initial load of the SPA, su ...

Using the _id String in a GraphQL query to retrieve information based on the Object ID stored in a

Encountering an issue with my graphql query not returning anything when sending the _id as a string. Interestingly, querying the DB using any other stored key (like name: "Account 1") works perfectly and returns the object. I've defined my Account sch ...

Is there a way to access the history of Vue routers?

I am looking for a way to determine if the Vue router has additional entries in its history that can be navigated back to. This information is crucial for deciding whether or not to execute the exit app function. The app should only navigate back to prev ...

Guide on inputting information into a dual-column table where one column is linked to the other

After successfully inserting data with hardcoded values to verify the relation between the 2 columns, I am now wondering if there is a way to reference the value of id in reply_id. This is how I manually inserted data: const { data, error } = await su ...