Add an element to an array using a dynamic variable as the key

I'm encountering an issue with a JavaScript array and a variable. My goal is to add to the array an object where the property name corresponds to the variable, but it should hold the value of that variable rather than treating it as a string. Here's the code I currently have:

array = [];
var x = 10;
array.push({x: y});

Unfortunately, in this setup, "x" gets stored as a string instead of representing the actual value of var x. I would greatly appreciate any assistance on this matter.

Answer №1

When working with object literals, it's important to remember that the property name is not treated as a variable and must be assigned using bracket notation.

let myObj = {};
myObj[key] = value;
myArray.push(myObj);

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

Update breadcrumbs dynamically by clicking on each horizontal panel

I've been dealing with a problem for the past 24 hours. I want to implement a horizontal accordion with breadcrumbs on a webpage. How can I achieve this dynamically, so that when a user clicks on any link in the accordion, the breadcrumbs update simul ...

Exploring Heroes in Angular 2: Retrieving Object Information by Clicking on <li> Items

Currently, I am delving into the documentation for an angular 4 project called "Tour of Heroes" which can be found at https://angular.io/docs/ts/latest/tutorial/toh-pt2.html. <li *ngFor="let hero of heroes" (click)="onSelect(hero)">{{hero.name}}< ...

Exploring the functionality of OpenLayers 5: Removing a map layer with a checkbox

I need assistance with removing a layer from a map using openlayers 5. I have successfully added the layer to the map using a checkbox. What I am looking for is that when the checkbox corresponding to the layer is checked, the layer will be displayed on th ...

Tips on utilizing React and Node to upload text as a file to Google Drive

Are you wondering how to incorporate React.js as the frontend and Node.js as the backend for uploading/reading files from Google Drive? In my attempts, I've tried writing a string as a text file and then uploading it to Google Drive by following this ...

Populate the array provided as a parameter within a bash function

I'm looking for a way to populate an array within a function without relying on a global variable. This function will be used multiple times with different arrays. I came across a discussion on passing arrays as arguments in Bash on Stack Overflow and ...

What is the process for embedding iframe content onto a main webpage?

I'm facing a challenge with an iframe on my page that contains important content. How can I add additional content to the page where this iframe is located? Any suggestions would be greatly appreciated. Thanks! ...

Creating an interactive time selection tool with two dropdown lists that are dependent on each other using HTML and JavaScript

Hi everyone, I am new to JavaScript. I am currently working on creating two dropdown lists, one for 'Start Time' and another for 'End Time'. These dropdown lists will display hours in a 24-hour format with intervals of 30 minutes. In t ...

How can I sum up each array elements using a forEach loop in JavaScript?

Check out my code snippet: var data = [[40, 20, 60], [20, 30, 10], [50, 75, 40]]; var averageData = []; data.forEach(function(entries) { entries.reduce(function(a, b) { return a + b[1]; }, 0); console.log(entries); }); I want to sum ...

Tips for displaying eslint error messages in the browser while working with reactjs

My usual method of setting up a project is using the create-react-app cli tool. I'm looking for a way to configure my ReactJS project to display ESLint errors and warnings directly in the browser, similar to how VueJS does it. With VueJS, any warning ...

.li click event not triggering after appending to DOM

When I add an li element to a ul using jQuery, it looks like this: $(".vocab-list").append( $('<li onclick="play_sound(\''+val['audioURL']+'\');" class="vocab-word" id="vocab_' + val['id']+ &a ...

Filtering through a vast number of data points over an extended period of time?

Exploring the possibility of applying two running filters to a substantial amount of data has led me to ponder about the effectiveness of creating variables dynamically. Despite common advice against it, I am considering if this approach might still be sui ...

Built-in functionalities in React.js

Here is a snippet that is working as expected: class Button extends React.Component { state = { counter : 0 } handleClick = () => { this.setState({ counter: this.state.counter+1 }) } render() { return ( <button ...

The challenge with Normalizr library in Redux and how to address it

I am currently attempting to utilize the Normalizr library by Paul Armstrong in order to flatten the Redux state. Below are the schema definitions: import { normalize, schema } from 'normalizr' const fooSchema = new schema.Entity('foos&apo ...

The act of employing `Function.prototype.run` within an Angular TypeScript class is deemed as illegitimate

Is there a way to globally define a new function called run within my Angular component as shown below? Function.prototype.run = function (delay: number) { // some content; }; However, the compiler shows an error that the Property 'run' does n ...

Check the validity of your JavaScript files with our convenient online tool!

Is there a website or online tool available to validate the syntax of JavaScript code in a file? I am experiencing problems with Internet Explorer 7 while running JavaScript, so I want to make sure my JavaScript file is valid. ...

Using Angular JS, apply multiple column filters within a table to refine the displayed data

I'm currently working on implementing a filter for multiple columns in a table that is being populated by the ng-repeat directive. <tr ng-repeat="descriptiveField in vm.descriptiveFieldList|filter:{name:vm.searchText}" ng-class-even="'even-bg ...

What is the best way to utilize a reduce function to eliminate the need for looping through an object in JavaScript?

Currently, my code looks like this: const weekdays = eachDay.map((day) => format(day, 'EEE')); let ret = { Su: '', Mo: '', Tu: '', We: '', Th: '', Fr: '', Sa: '' }; w ...

Update the JSON output format for auto-suggestion feature

I am looking to modify my JSON output, currently structured as: [ { masterCardNo: 90363.01 }, { masterCardNo: 90363.02 }, { masterCardNo: 90363004 }, { masterCardNo: 90363004 }, { masterCardNo: 90363004 }, { masterCardN ...

Having trouble locating the CSS and JavaScript files within my Spring Maven project

I have a Spring framework application with a Maven project. In addition, I have CSS and JavaScript files under the WEB-INF folder. When attempting to link the JavaScript and CSS files like this: <link rel="stylesheet" href="../allDesign/js/vendor/anims ...

Sending a Django form using AJAX and jQuery: A step-by-step guide

After researching various tutorials on django AJAX forms, I've found that each one offers a different method, but none of them seem simple. Being new to AJAX, I'm feeling a bit confused by the complexity involved. In my specific case, I have a m ...