Is there a way to utilize a variable as a key within an object?

Can this be done? Take a look at a practical example from the real world:

var userKey = "userIdKey";

chrome.storage.sync.set({ userKey: "Hello World" }, function () {
    chrome.storage.sync.get(userKey, function (data) {
        console.log("In sync:", data);
    });

    console.log("Success");
});

This specific example is failing because the getter is expecting "userIdKey" while the setter is treating the variable as "userKey" literally.

UPDATE: I understand that variables can be accessed using array notation. The example I provided demonstrates the creation of an object. My goal is to ensure consistency in using the same key for both getting and setting values, rather than depending on keeping two string constants in sync.

Answer №1

An appropriate method to achieve this is as follows:

    let keyword = "example";
    Object.defineProperty(obj, keyword, {
        get: function() {return this.getMonth() },
        set: function(m) {this.setMonth(m) }
    });

In your specific scenario:

chrome.storage.sync.defineProperty(this, userInputKey, {
    get: function() {return this[userInputKey];},
    set: function(val) {this[userInputKey] = val};
});

For further information on this topic, visit THIS LINK. Note that while Object.prototype.defineProperty may not be accessible in legacy mode, the polyfill can be utilized as

Object.prototype.__defineGetter__
and
Object.prototype.__defineSetter__
.

Answer №2

let newObject = {},
    keyName = 'Bar',
    newObject[keyName] = 'Qux';

console.log(newObject[keyName]);

Answer №3

You can access it as if it were an array:

myObject['Foo']

To assign a value:

myObject['Foo'] = "Bar"

Alternatively, you can use a variable:

var key = "Foo";
myObject[key] = "Bar"

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

Pull in class definitions from the index.js file within the node_modules directory

In my project, I have the package called "diagram-js" in the node_modules. The file node_modules/diagram-js/lib/model/index.js contains multiple class definitions as shown below: /** * @namespace djs.model */ /** * @memberOf djs.model */ /** * The b ...

Results not showing up

After attempting to incorporate the scores into a table, I am facing an issue where they are not displaying. Can anyone offer assistance with this problem? I am currently hosting on GitHub Pages. File: https://raw.githubusercontent.com/Eternal-Network/Ete ...

The performance of three.js PointsMaterial is sluggish when utilizing large sprites or shapes, causing a decrease in overall

Currently, I am handling a point cloud with approximately 60,000 vertices. Interestingly, when I view the cloud at a smaller scale, performance remains acceptable. However, as soon as I zoom in and larger sprites/plans/points become visible on the screen, ...

What causes axios to return a z_buf_error?

I've encountered an issue with axios returning an error cause: Error: unexpected end of file at BrotliDecoder.zlibOnError [as onerror] (node:zlib:189:17) { errno: -5, code: 'Z_BUF_ERROR' I'm puzzled as to why this functio ...

Issue arises when trying to implement sidebar navigation in Angular with Materialize CSS

Just starting my Angular journey and running into some trouble trying to set up a practical and responsive menu using SidebarNav and Dropdown. I used CLI to install and configure angular2-materialize and materialize-css. To create the menu, I made a comp ...

Ways to extract specific data from a Json response

Currently, I am engaged in a school project that involves manipulating json data from the Google Geocoding API. I am facing a dilemma on how to properly store the "formatted_address" (as shown below) from the API response so that I can utilize this inform ...

Encountered an issue with the Mongoose Schema method: The model method is not recognized as a

Here are two Mongoose model schemas that I am working with. The LabReport model includes an array that references the SoilLab model. Within the SoilLab model, there is a static method that was initially used to choose which fields to display when retrievin ...

A guide to setting properties using a Proxy object

Within my class, I have included a Proxy which is structured as follows: export class Row<T extends ModelItems> { private _row: T = <T>{} public constructor(rowItems?: T) { if (rowItems) { this._row = rowItems } return new Proxy( ...

Exploring solutions for handling asynchronous issues with vue3-google-map

While working with a Vue library for managing Maps called vue3-google-map, I encountered an issue when trying to define certain polylines that would not allow me to select the center of the marked area: Here is my map template: <template> <Goo ...

While working with AJAX, the variable value remains static and is not refreshed

My jQuery code successfully calls a REST Service and handles the response in the AJAX Success event. However, I'm facing an issue where the variable "SelectedVal" (document.getElementById('Text1').value) is not getting updated with each cli ...

Apply the style when the page loads and remove it when clicked

There is a feature in my code that adds a class when an element with the class .tab is clicked. $(function() { $(".tab").click(function() { $(this).addClass('blueback'); $(".tab").not($(this)).removeClass('bl ...

Incorporating lazy loading for diverse content to enhance pagination

I'm currently using jpaginate for pagination on a large dataset, but I've noticed that all the content loads at once. Is there a jQuery plugin available that will only load the content for the current page? ...

Having difficulty launching a new window within an app built with Electron and Nexjs (Nextron)

Attempting to launch a (Nextjs-generated) page in a new window is causing an error message to appear: Uncaught ReferenceError: global is not defined Here is the full error: react-refresh.js?ts=1665849319975:10 Uncaught ReferenceError: global is not de ...

jquery toggle for partial visibility not functioning properly

Can jquery sliding functions be used to partially show and hide content? In this scenario, there is a list with 7 items but only the first two are visible initially, while the rest are hidden. The goal is to have all 7 items show when the user clicks to v ...

Modify information on the user interface without the need to refresh the page

Is there a way to update data on the UI without having to refresh the screen in a web application built with Node.js? I'm looking to make only specific changes on the screen. Additionally, how can I ensure that the data displayed on the screen is upda ...

A guide on iterating through a JSON object in Vue and Javascript to retrieve keys and values, checking if they are either distinct or null

Looking for a way to iterate through a JSON object that may or may not have properties fields, which can be null or contain various configurations. I need to display it in a code block. Below is the example JSON data: "grade": [ { ...

Chrome experiences a crash during regular expression matching operations

I have a challenge where I am attempting to validate 50 email addresses separated by commas using regex. Strangely, every time I run this operation, Chrome crashes. However, Safari seems to handle it without any issues. Below is the code snippet that I am ...

Executing an AngularJS function using regular JavaScript code

I am currently working with AngularJS and Typescript. I have integrated an external library into my project and now I need to call an AngularJS method from that library, which is written in vanilla JavaScript. I tried following this example, but unfortunat ...

Tips for transferring PHP variable from a drop down menu

Hello, I am currently working on creating a dropdown menu using the <select> tag. My goal is to have it so that when someone clicks on one of the options in the dropdown, a new window opens. Additionally, I want the PHP variable from the main page to ...

Utilizing Angular 1.5 and ES6 to Enhance Dependency Injection

Hi there, I am currently exploring Angular and attempting to integrate ES6 into my workflow. I seem to be facing an issue with dependency injection where I cannot seem to get it working as expected. Here is a snippet from my index.js file: import ...