Creating JSON with dynamically changing properties using JavaScript

I am currently working with the following JavaScript code:

var date = record.get('Date'),
    day = date.getDate(),
    month = date.getMonth(),
    year = date.getFullYear();

var formattedDate = year + '-' + month + '-' + day;

datePicker.selectedDates = {
    formattedDate: formattedDate
};

At this moment, the value of selectedDates is: formattedDate: '2014-7-27'

However, I would like the result to be '2014-7-27' : '2014-7-27'

Any suggestions on how to achieve this?

Answer №1

At the moment, there isn't a syntax that allows you to do the following:

var key = "foo", val = "bar";
var obj = {
  [key]: val // results in a syntax error
}

However, you can achieve the same result by using:

var key = "foo", val = "bar";
var obj = {};
obj[key] = val;

A helpful approach could be to create a function that will handle this repetitive code for you. Consider implementing something like this:

var obj = build_object(key, val, key2, val2, ...);

In ES6, we have access to enhanced object literals which provide some additional functionality: , although it may not fulfill all your requirements.

var a = "a", b = "b";
var obj = { a, b, func() {
  return "foo"
} } // { a: "a", b: "b", "func": function () { .. } }

Answer №2

One way to incorporate dynamic key properties into an object is by utilizing square bracket notation.

calendarTracker.chosenDates = {}
calendarTracker.chosenDates[chosenDate] = chosenValue;

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

Targeting a single element in a list with JavaScript operations

I'm facing a challenge with my current code (coffeescript) on Rails. I have a list of subscription videos being generated by Rails, and I want a popup to appear only when hovering over a specific video. However, every video in the list has the same cl ...

Incorporating D3's library functions into Rxjs for seamless integration with Observables

I'm really struggling with this concept and could use some guidance. My goal is to monitor when data is fetched, but I seem to have confused the process. Here's what I've tried so far: Using d3.tsv for an ajax request. var test = Rx.Observa ...

Troubleshooting Google Chrome Extension: chrome.storage.sync.get malfunctioning

Could anyone help me troubleshoot my code issue? I successfully save the data, but when trying to load it, the saved data cannot be found: Here is the code snippet: $('#SaveSet').click(function() { var theValue = $('#col').val(); ...

Transmit information from node.js to the frontend utilizing only raw JavaScript

Seeking guidance on sending data object from a Node.js server to a JS file for frontend use. In the main.js file, DOM manipulation is performed. The following request is made: let dataName = []; let request = async ('http://localhost:3000/') =& ...

Structure for using Node modules

I've been having some trouble understanding how to set up Stripe for my app. I'm unsure about the implementation of the module in the paymentController file. Typically, when using a module, I would require it at the top of the file to use it effe ...

Access the value of a JavaScript global variable using Selenium in Python

I need to access a value from a global variable in JavaScript: clearInterval(countdownTimerTHx); var saniye_thx = 298 // <--- Variable here function secondPassedTHx() { https://i.sstatic.net/odIbh.png My goal is to retrieve the value " ...

React-native - Dropdownpicker - Error: Unable to retrieve label for selected choice

I'm encountering an issue with DropDownPicker in my react-native project during page load Here is the code snippet where I am using DropDownPicker: <DropDownPicker items={[ { la ...

Ajax cannot seem to come to a resolution

After completing my learning on Ajax, I decided to work on a simple project - a port scanner. However, I am facing issues with it as it is not working properly. The only message that pops up is 'Scan started' and I can't figure out what the ...

two separate .Click() functions operating in unison rather than independently - jquery

After selecting the filter tabs, they work perfectly fine but always scroll the page to the top. Can someone please take a look at the code below and point out what mistake I've made in it? On the other hand, the Back-to-Top function is working as in ...

Ways to incorporate various time intervals between individual slides in bxslider

Can individual delay times be set between each slide in a bxslider? For example, having a 1000ms delay between the 1st and 2nd slide, and a 2000ms delay between the 3rd and 4th slide. Is it feasible to achieve this? ...

Retrieve the data from the file input field

I am attempting to dynamically change the value of an input type text based on the input type file selection. Despite my efforts with the code below, I have been unable to find a solution to this issue. HTML: <input type="text" name="imagem" class="fi ...

Notification prompt when removing items

I currently have a table set up with a delete <a> tag that allows users to delete data. I would like to add a confirmation message asking the user if they are sure they want to delete before proceeding. I attempted to achieve this using JavaScript bu ...

Reorganize components in MongoDB record

Description: Each customer object includes a name field. A line object is comprised of the following fields: inLine - an array of customers currentCustomer - a customer object processed - an array of customers The 'line' collection stores doc ...

Is it possible to set a single variable value for multiple attributes simultaneously in Javascript?

I would like to specify the horizontal padding of a styled element as variable 'x' and the vertical padding as variable 'y'. Here's one way to achieve this: var docex = document.getElementById.style; docex.paddingTop = y; docex.pa ...

Leveraging database information in JavaScript through JSON

I want to display some data from my database using Javascript. Below is the PHP script I have written: $arrayDatabase = array(); $statement = $link->prepare("SELECT project.ID, project.titel, project.subtitel, project.plaatje, project.beschrijving, pr ...

Upon refreshing the datatable, I encountered a issue where the checkbox cannot be selected

After updating my data table with new content through an AJAX request, I am facing an issue where I am unable to select the check-boxes in the table. I use a class selector to choose the rows that contain multiple check-boxes. The select event is placed in ...

What is causing the overwhelming reaction when using window.open() to open the same file?

I'm having trouble when trying to print a web page using JavaScript. The window.open() function does not load the style sheets of the same file. Here is my JavaScript code: function Print() { printWindow = window.open("", "mywindow", "location=1 ...

Jquery - Ajax: Error in Syntax JSON.parse: character not expected

I am encountering an issue with parsing JSON data on my client-side code. The JSON received from the server looks like this: [{"name":"Bubble Witch Saga 2","impressions":10749},{"name":"Grinder","impressions":11284},{"name":"Loovoo","impressions":12336},{" ...

Unable to extract all advertisements from Facebook Marketplace

https://i.stack.imgur.com/xEhsS.jpg I'm currently attempting to scrape listings from Facebook marketplace, however, only the first listing is being scraped. Does anyone have any suggestions on how I can scrape the entire list of listings? CODE (async ...

Issues arise when submitting the form on a web page with an MVC 4 partial view, causing the page

Scenario: I am currently working on a C#/MVC 4 project where I have a view that includes a partial view. The main view consists of a form with a submit button, and the partial view is initially hidden but can be displayed by selecting a checkbox. Problem: ...