using an object's key as a variable in JavaScript

Is it possible to reference an object's key as a variable and then modify its value? I am experimenting with the following:

const obj = {
  x: {
    y: {
      z: 'test'
    }
  }
}

const func = () => {
  let root = obj['x'];
  root = 'test 2';
}

func();

console.log(obj);

I am currently working on a recursive function to change root to something like obj['x']['y'].

Answer №1

If I am interpreting your inquiry correctly, the response is most likely "not without resorting to some unconventional methods." It appears that you are inquiring about this scenario:

const obj = {
  x: {
    y: {
      z: 'test'
    }
  }
}

You wish to store obj.x (or alternatively, obj['x']) into a variable such that modifying that variable will result in a change to the x field of object

obj</code. This task cannot be accomplished as desired. Once you establish the connection with:</p>

<pre><code>let root = obj.x

Any subsequent reassignment to root will not affect

obj</code at all; this means that <code>root
acts independently from
obj</code. Visualizing it might help clarify this concept. Nevertheless, <code>root
essentially serves as a reference to obj.x, so if you were to execute:

root.y = 'test 2'

This action indeed alters obj.x.y.

However, it is important to note that you are unable to assign obj.x to a variable and then leverage that variable to modify the x field within

obj</code. Modifications can only be made to fields WITHIN <code>obj.x
. In contrast to languages like C++, JavaScript lacks the capability to create aliases or manipulate lvalues.

If your intention is truly to update the x property of

obj</code, you should solely store the string <code>x
in a variable like so:

root = 'x'

Then you could proceed with the following:

obj[root] = 'a new value for obj.x'

This operation will bring about changes to obj.x. However, bear in mind that evaluating obj.x first and using that result to modify

obj.x</code is not a feasible approach. Well, unless you delve into complicated tactics like this:</p>

<pre><code>root = 'obj.x';
eval(`${root} = 'a new value for obj.x';`);

Steer clear of such convoluted methods.

Moreover, if obj itself was also a variable, you could carry out the following procedure:

receiver = obj;
prop = 'x';
Reflect.set(receiver, prop, 'the new value')

Hopefully, my interpretation aligns with your objectives. Regardless, perhaps this explanation may spark some ideas.

Answer №2

function updateRoot() {
  let rootValue = obj['x'];
  rootValue = 'test 2';
}

This function changes the value of the variable rootValue without affecting the object. To update the object directly, use the following code:

obj['x'] = 'test 2'

const obj = {
  x: {
    y: {
      z: 'test'
    }
  }
}

function updateObject() {
  obj['x'] = 'test 2';
}

updateObject();

console.log(obj);

Alternatively, you can modify a specific value within the object using the rootValue variable:

const obj = {
  x: {
    y: {
      z: 'test'
    }
  }
}

function updateFieldValue() {
  let rootValue = obj['x'];
  rootValue['y'] = 'test 3';
}

updateFieldValue();

console.log(obj);

Answer №3

Simply transfer the data

const newObj = { a: { b: { c: 'example' } } }

remove Object.assign(newObj, {freshKey: newObj.staleKey }).staleKey;

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

Create a dynamic Bootstrap progress bar that smoothly transitions from 0 to 100%

I am currently utilizing Twitter Bootstrap to construct my webpage. Here is the snippet of HTML code I have: <div class="btn-group"> <button type="button" class="btn btn-success">Connect</button> <button type="button" class=" ...

JSON Novice - persistently storing data in JSON during browser refreshes

My AJAX poll was set up following a guide found here: http://www.w3schools.com/php/php_ajax_poll.asp Instead of storing the poll entries from an HTML radio button in an array within a text file as demonstrated in the tutorial, I wanted to save them in a J ...

Adding Bootstrap modal content to a webpage before it renders is a simple process that involves preloading the

When using Bootstrap modal, is it possible to load a remote URL along with the parent page without needing to click on a button? ...

How can I ensure that a button remains fixed at the bottom of a Material UI React Component?

I am currently working on developing a layout for a web application, and I have encountered an issue that I am struggling to resolve. The structure of my grid is as follows: https://i.sstatic.net/TEU2a.png My goal is to ensure that each section inside t ...

Retrieving the input[text] value in TypeScript before trimming any special characters

One of the tasks I am working on involves a form where users can input text that may contain special characters such as \n, \t, and so on. My objective is to replace these special characters and then update the value of the input field accordingl ...

React: Enhancing the URL with a File Name

Has anyone encountered the issue where index.css is showing up as the :id in axios requests? I recently configured a proxy in React to deploy to Heroku with the setting "proxy": "http://localhost:3001/". However, after setting up the p ...

What is the best way to arrange this by DateTransaction using a dropdown list?

Requesting assistance from the PHP community! I'm a newbie and in need of your expertise. My task is to create a dropdown list that sorts a table based on the DateTransaction column, with options ranging from January to December. Here is the code sni ...

Avoid inputting characters and triggering a new event

I am facing an issue with capturing the "keydown" event and then changing the focus to the last active element. Whenever I try to set the focus to a specific element within the function that captures the event, either the "input" element receives a "char" ...

The CSS files are not loading automatically in my React application using Vite

I am facing an issue with importing css and js files into a view in React using vite. The styles are not loading properly, and I have to keep commenting and uncommenting the imports in my code for them to be recognized when entering the view. Below is a s ...

Collecting information from form submissions, accessing data from the database, and displaying the results

I am currently working on a project using nodejs, express, and mongodb within the cloud9 IDE. My goal is to create a page with a form that allows users to input data, search for corresponding information in the database, and display that data on the same ...

Encountering the "Error: JSON.parse: unexpected character" when trying to retrieve JSON data using AngularJS

I've been struggling with this issue for the past few days. Every time I attempt to fetch a JSON object using Angular's $http.get method, I encounter the error message "Error: JSON.parse: unexpected character". The JSON data is generated using P ...

Hold on, the document will be available momentarily

There is a backend process that creates a file (which may take up to 1 minute). I created a function to check if the file is ready. function checkForFile() { $.ajax({ url: '/check/', // check if file exists success: function(data) { ...

Issue with Ruby Selenium Webdriver: Unable to locate attributes for AngularJS Radio Buttons

I am having trouble detecting the presence of the "checked" attribute on a radio button. Here are the two radio buttons in question: Radio Buttons These are the attributes of the elements: <input type="radio" ng-change="logConsent(true)" ng-model="xx ...

Conceal the cursor within a NodeJS blessed application

I am struggling to hide the cursor in my app. I have attempted various methods like: cursor: { color: "black", blink: false, artificial: true, }, I even tried using the following code inside the screen object, but it didn't work: v ...

Displaying the server's feedback upon successfully uploading a file onto the server

I am utilizing an HTML5 input control that allows users to upload a .csv file: <input id="ImportFile" type="file" name="ImportFile" data-val="true" data-val-required="Please select a file" title="Browse for a file to upload" /> This input control i ...

Ways to guide users through a single-page website using the URL bar

I currently have a one-page website with links like <a href="#block1">link1</a>. When clicked, the browser address bar displays site.com/#block1 I am looking to modify this so that the browser shows site.com/block1, and when the link is clicke ...

Unforeseen issue encountered while utilizing node proxy

While running the program below, I encountered an error. The application worked fine locally but when I tried to access it in the browser through localhost:3000, this error popped up on the console... **Error: connect ECONNREFUSED** at exports._errnoE ...

Switch the Ionic Slide Box to the "does-continue" setting

Currently in the process of constructing a slide-box containing numerous items. I've borrowed the code from the example provided here for an infinite number of items, and it's performing well. However, I have a considerable yet finite amount of ...

Any tips on how to retrieve the data from an AJAX request using vanilla JavaScript?

After successfully implementing my first AJAX call last week, I am now faced with a new challenge. This time, I need to not only change something onSuccess but also access the returned data. <script type="text/javascript"> function showMessage(j ...

In Chrome, the $http GET request fails to send the JSESSIONID, but it functions properly on Firefox with AngularJS

Here is the code snippet I am working with: $http({ 'method': 'GET', 'url': 'http://www.example.com', 'withCredentials': true, headers: { 'Content-type': &apo ...