Embed the variable directly within the JSON structure

My goal is to dynamically create a JavaScript object using object initializer notation, but with keys taken from a config object. Instead of the traditional method:

var obj = {
  'key' : 'some value'
};

I envision something like this:

var config = {
  myKeyName: 'key'
};

var obj = {
  config.myKeyName : 'some value' // this is just an illustration
};

The challenge lies in how to incorporate the value of config.myKeyName in this particular scenario.

Is there a way to achieve this?

Update: I am familiar with using indexing ([]), but that may not be feasible for deeply nested objects.

Answer №1

Based on the feedback and revisions you've made, it appears that your main inquiry is about the possibility of utilizing dynamic keys within deeply nested objects while still adhering to the object initializer syntax.

For instance, rather than the traditional approach:

var key1 = "x", key2 = "y", key3 = "z", object;
object = {}
object[key1] = {};
object[key1][key2] = {};
object[key1][key2][key3] = 42;

You are exploring a scenario like this:

var object = {
    /*using key1 dynamically to retrieve "x"*/: {
        /*using key2 dynamically to retrieve "y"*/: {
            /*using key3 dynamically to retrieve "z"*/: 42
        }
    }
};

Regrettably, the answer remains negative; there is no approach to achieve this without resorting to eval. The keys must be fixed within an object initializer and cannot be ascertained from variables. The notation of [] remains the optimal method for specifying a property name with a string. Another bulkier option is Object.defineProperty, but it's limited to ES5. Given your intricate nested structures, a recursive factory function seems to be the most suitable solution.

Answer №2

One way to dynamically access a property is by using the square bracket syntax. For instance, if config.keyName contains the value "hello":

var obj = {};
obj[config.keyName] = "some value";

/* This is the same as:

   var obj = {
       hello: "some value"
   };
*/

Additionally, it is important to clarify that this code is creating a JavaScript object literal, not JSON. JSON is a textual data format commonly used for data exchange, although it does share some similarities with JavaScript object literals.

Answer №3

In the world of JavaScript, there is no such concept as "JSON notation." Instead, it is referred to as object literal notation. JSON actually utilizes a portion of the JavaScript notation, not the other way around.

When working with object literals, it is important to note that you cannot use variables directly for property names. Instead, you must utilize property indexing to add properties to the object:

var obj = {};
obj[settings.myKeyName] = "some content";

Answer №4

const myObj = {}

myObj[settings.theKeyName] = 'a certain string';

Answer №5

let configuration = {
  keyLabel: 'key'
};

let object = {
  'configuration.keyLabel' : 'some data' // pay attention to the quotation marks on the key
};
//console.log(object);

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

Guide on importing npm packages without TypeScript definitions while still enabling IDE to provide intelligent code completion features

I am currently utilizing an npm package that lacks type definitions for TypeScript. Specifically, I'm working with the react-google-maps library. Following their recommended approach, I have imported the following components from the package: import ...

Issue with SVG on tainted canvas causes IE security error when using toDataURL

In my Angular JS directive, I have implemented a feature to export SVGs to PNG. While this functionality works seamlessly in most browsers, it encounters a security error in IE. Despite my numerous attempts to troubleshoot the issue, I have been unable to ...

Communicate with a PHP page using Volley for both sending and receiving data

I am planning to pass a parameter to a PHP page, and after performing specific processing on it, I want to receive a series of parameters in JSON format from the same page. Below is the code I have written for this: //Displaying progress dialog final Prog ...

Utilizing the Linux grep command to extract key values from a JSON file

My dilemma lies in handling the JSON output I have, which contains a list of objects stored within a variable (I hope I expressed that correctly). I've tried executing a curl command to obtain the output, but unfortunately, I'm unable to share i ...

Can an HTML DOM object be converted to a JSON string using JSON.stringify in JavaScript?

Trying to fetch an external HTML file and convert its body content into a string has been giving me unexpected results. Is there a way to achieve this successfully? var xhr = new XMLHttpRequest(); function loadFile(){ xhr.open("GET", 'index.html ...

Express server consistently receives JSON requests that contain no data in the request body

Currently, I am in the process of developing a small server and website using Express. At this point, my goal is to send a POST request to my Express server with basic credentials encoded as JSON. The issue I am facing is that no matter what I attempt, th ...

What could be causing the issue with dayjs dynamic importing in TypeScript?

Currently, I am developing a web screen within a .NET application and facing an issue with sending datetime preferences from the system to the web screen using CefSharp settings. AcceptLanguageList = CultureInfo.CurrentUICulture.Name In my TypeScript code ...

Having trouble getting a div to slide to the left on hover and collapse on mouseout using Jquery?

Hey there! I need some assistance in completing this code snippet. I have a div with overflow:hidden and a margin-left of 82px. Inside it, there is a share link and a ul list containing three external links. When I hover over the share link, everything w ...

Discovering insights from JSON files in Data Lake Gen 2 using Azure Data Factory

Currently, I have an ADF pipeline that loads raw log data in the form of JSON files into a Data Lake Gen 2 container. Our objective now is to extract valuable information from these JSON files. My aim is to discover the most efficient method for extractin ...

Monitor and adjust variables simultaneously using AngularJS

My goal is to dynamically calculate and display values based on two other variables in real time. I've successfully managed to track one variable, but not both simultaneously. $scope.color_slider_bar = { value:0, minValue: 0, maxValue: ...

Refreshing the page causes JavaScript to fail loading

Recently, I encountered a puzzling error. Upon visiting this link The carousel fails to load properly near the bottom of the page. However, if you click on the logo or navigate back to the home page, it works fine. Additionally, performing a command + r ...

Utilize Node.js to simultaneously connect with several APIs

Consider a scenario where multiple APIs need to be called in parallel using promise.all(). The issue arises when promise.all() rejects if any API fails. In this case, instead of giving up on failed APIs, I want to retry them until they succeed. However, ...

Checking the validity of the primary key information in the destination table using JSON source data and replacing it with updated values

Information in Json format { "Root": [ { "Column": "Primary_key", "CurrentValue": "3456", "NewValue": null }, { "Column": "FirstName", "CurrentValue": & ...

Stop automatic form submissions from the enter key

My live chat messaging system is experiencing an issue where the page refreshes every time a user presses the enter button. I attempted to use prevent default code, but it did not work for me. I'm new to website programming, so if there are any proble ...

I am in need of a datepicker for my project that will display the END date as the current date and set the START date as 7 days before the END date

$(document).ready(function () { $("#end").datepicker({ dateFormat: "dd-M-yy", minDate: 0, onSelect: function () { var start = $('#start'); var startDate = $(this).datepicker('getDate') ...

Measuring Internet speed using Node.js

Is there a way to measure internet speed in server-side node.js? I am currently sending the current timestamp from the client side while making an http request. Client side code: var image = document.createElement("img"); image.width = 1; i ...

ReactJs allows for fluid scroll animations that persist as long as the mouse is clicked or a button

Just some background information: I'm aiming to replicate the scrolling effect seen in Etsy's product image thumbnails carousel. Essentially, when you hover over the top part of the div, it automatically scrolls down until the last image is reve ...

Interactive hover text appears when you mouse over the SVG path

Does anyone know the simplest way to display sample text when hovering over an svg path? Below is my CSS code: <style> path:hover{ fill:yellow;stroke:blue; } .available { fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;strok ...

Using a self-invoking function in JavaScript with addEventListener

I'm struggling to get an Event Listener to self invoke a function and work correctly. Although the following code runs the function, the Event Listener is not functioning as expected: window.addEventListener("resize", (function () { document.getElem ...

What is the best way to animate changes to a background image using jQuery?

Exploring the possibilities of creating a unique visual effect reminiscent of a pulsing heartbeat for a button. I'm under the impression that achieving this is beyond the scope of CSS. Can anyone shed light on how to implement an animated background ...