JavaScript code to place variables into an array with included variables

Looking for a solution:

const myArray = []

myArray.push( { "bob" : { "banana" : "yellow" } })

console.log(myArray)

Output:

{
    "bob": {
        "banana": "yellow"
    }
}

Attempting a modification:

const myArray = []

const name = "bob"
const fruit = "banana"
const fruitcolor = "yellow"

myArray.push( { name : { fruit : fruitcolor } })

console.log(myArray)

Unfortunately, the result is not as expected. Any suggestions on how to correct this issue would be greatly appreciated.

Thank you!

Answer №1

If you would like to designate a string as a key for an object, you must utilize the bracket notation

Substitute

myArray.push( { name : { fruit : fruitcolor } })

with :

myArray.push( { [name] : { [fruit] : fruitcolor } })

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

Utilize tags as properties in Vue.js by selecting them

I am attempting to retrieve a value from a select tag and use it in an object property. Below is the HTML code: <div id="app"> <h3>{{title}}</h3> <div class="form"> <div class="form-group"> <div ...

The bundle.js file encountered an issue while running UglifyJs, expecting a name

I have been attempting to utilize UglifyJS to compress/minimize my bundle.js file. However, when executing webpack -p, I encountered the following error message: ERROR in bundle.js from UglifyJs Name expected [bundle.js:105519,6] The line causing the iss ...

jQuery click event handler performing no action

I am encountering an issue with the input on my index page: <input type="button" name="goReplaceAll" value="Go" id="allReplaceGo" style="cursor:hand;" /> There is an onclick call from jQuery as follows: $(document).ready(function() { $(&ap ...

View complex response objects in Postman as easily digestible tables

I am interested in displaying the data provided below as a table using Postman Tests. The table should have columns for product, price, and quantity, with Items listed in rows. It's important to note that there may be multiple shippingGroups within th ...

Hiding a parent DIV in JS based on specific content: Here's how

I need help figuring out how to hide multiple parent DIVs based on the content of a specific child DIV. Here's an example: <div class="report-per-day"> <div class="report-day">26 May 2022</div> <div class=" ...

Sorting through a collection by using a nested array

I've been working on optimizing my code to prevent making new http requests to my API every time I need to filter results. Currently, I have an array called pageContent that is populated with data from an API fetch when the page loads. Each object in ...

In the production mode, Webpack doesn't compile any code

I recently followed the typescript guide at https://webpack.js.org/guides/typescript/ After running webpack in "production" mode, I noticed that it emitted very minimal output. Below is the code from my src/index.ts file: export function foo() { return ...

Error: The function referenced is not defined when the page loads

Trying to incorporate two different script tags in a single HTML page has been quite a task for me. The first script tag contains the location of a JS file that I need to use for a specific function, while the second script tag is where I have written anot ...

I am facing an issue with updating the state dynamically within a useState object

Within my useState, there is an object containing a variety of values. I have an input field and am dynamically setting its value to useState[key], which works fine. However, the issue arises when I try to update these values. When I call onChange and use ...

How can I incorporate fetch into my code using VSCode?

I am completely new to using JS. I want to incorporate fetch in VSCode, but I'm having trouble importing it. When I try: import fetch from "node-fetch"; I get this error: (node:19856) Warning: To load an ES module, set "type": &q ...

Maximizing the power of datatables with ajax integration

Exploring pagination with AJAX on datatables.net is something I want to try. I have two input fields where users can enter start and end dates, followed by the table structure below: <table class="table table-hover" id="example"> < ...

I am facing an issue with my Angular 11 CLI application while trying to set it up with Jest. The specific error message I am encountering is: "TypeError: Cannot read property

Having issues with my Angular 11 cli app and Jest integration. Whenever I run npm run test, specifically jest --updateSnapshot, I encounter the following error in my terminal: Error: TypeError: Cannot read property 'paths' of undefined Here is ...

Is it possible to deactivate a button using jQuery without changing its visibility to transparent?

In my current project, I am utilizing jQuery and exploring its unique methods. I have a scenario where I need to disable two buttons based on a specific condition: if (...condition...) { $('button#submit, #hint').prop("disabled", true); } Ho ...

The target for CountUp is not defined in React.js and is either null or undefined

I'm experiencing an issue with React.js while using the CountUp library. I've tried everything I can think of, but so far, nothing has worked. I even created a state to check if the component is ready to render CountUp. I'm unsure whether t ...

How about using jQuery to display information alerts instead of the traditional alert function

Is there a way to display an alert within the login page itself if the login fails, instead of using a popup? error: function(data, status, xhr) { alert("Login failed."); } ...

What are the best techniques for organizing SCSS in Next.js?

There are multiple pages with some unused items. Is there a method to search and delete all the items based on their classname? Appreciate any assistance you can provide! ...

Applying the spread operator in the map function for copying objects

In my Angular application, I am attempting to copy an object and add a new property using the spread operator. To add the new property, I have created a method called 'addNewProperty(name)' which returns the property and its value. However, when ...

Create an additional column in HTML using Bootstrap styling

I am currently working on a CRUD form (using PHPMyAdmin for the database), developed in HTML, JavaScript, and PHP. The queries are executed using jQuery. I am facing an issue with my code - whenever I add a new column to my table, the formatting gets messe ...

Encountered an error while running the `npx-create-react-app my-app` command in

When attempting to run 'npx create-react-app my-app', the following error message is displayed: 'npx' is not recognized as the name of a cmdlet, function, script file, or operable program. Double check the spelling and path included to ...

Using Jquery Functions within Codeigniter

I am facing an issue with calling a function containing jQuery script within an if-else statement. Below is the codeignitor view code: Code if($osoption == "windows") { ?> <script> windows(); </script> <? ...