Utilizing JavaScript regex to transform bracket [ ] notation into dot notation

I need to convert variables from the format variableName[field1][field2] to variableName.field1.field2

This conversion is necessary because users can input variable names in the user interface, and I want to avoid using eval() directly. Instead, I have implemented a function for this purpose:

function getDescendantProp(obj, desc) {
   var arr = desc.split(".");

   while (arr.length) {
       obj = obj[arr.shift()];
   }
   return obj;
}

Using this function allows me to retrieve the value of the variable without executing code at runtime. However, it does not support variables specified within square brackets [ ].

Answer №1

Simple regular expression for transforming it into dots

let text = "varName[fieldA][fieldB]"
console.log(text.replace(/\[([^\]]+)\]/g, '.$1'))

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

Encountering a "Module Not Found" Error when attempting to execute a basic "Hello World" script

I attempted to run myfirst.js program from the terminal using the specified directory and command. I expected a window to open up or a browser popup. Upon typing node myfirst.js in the terminal within the same directory, an error message was displayed: no ...

Ways to transfer data through the javascript success function in traditional CodeIgniter

Currently, I am working with an aging CodeIgniter application. I am trying to implement an onchange function that retrieves data from the controller and displays it in an input field that is part of an array. This is a snippet of the code on the view page ...

Challenges with browsing navigation in Selenium WebDriver

Recently, I began my journey of learning selenium WebDriver. In an attempt to automate the task of logging into an account using the Firefox browser, I encountered a discrepancy. Manually opening the browser and clicking on the login link from the homepag ...

Success is returned as AJAX error

My AJAX call is returning an error as Success instead of a JSON error from ASP.NET MVC. Can someone please advise on how I can resolve this issue? Thank you. [HttpPost] public JsonResult Register(int EventID) { try { ...

Is there a way to stop the dropdown menu from disappearing when clicking on a popover that was activated from the dropdown?

Are you familiar with creating a popover that is triggered by a dropdown menu using the Twitter Bootstrap javascript components? Could you provide guidance on how to prevent the dropdown menu from closing when a user clicks on the popover? For reference, ...

When accessing the route "/[locale]", make sure to await the `params` object before utilizing its properties like `params.locale`

Currently, I am developing a Next.js 15 application utilizing the new App Router (app directory) with dynamic route localization. Within my project, I have implemented a [locale] directory to manage multiple language routes and utilize the params object to ...

AngularJS Error: Attempting to Access Undefined Object - Jasmine Testing

Encountering an error while running Jasmine tests when trying to mock/spy on an API call in the tests. Below is the code snippet responsible for calling the API: UploadedReleasesController.$inject = ['$log', '$scope', '$filter&apo ...

"An empty array in PowerShell will always yield a count of 1 when using the

When using .Count to check the number of items in an empty array like this: $theNames = @() $theTotalNames = $theNames.Count The result is 0, as expected. However, in a situation where I use .Count to check the contents of what appears to be an empty ar ...

Using regular expressions to parse CustomLog format in PHP

I am currently working on parsing a CustomLog format that appears as follows: LogFormat "%v %{X-Forwarded-For}i %h %l %u %t \"%r\" %>s %b" MyCustomLog The log entry is formatted like this, with a comma separating the IP addresses listed in t ...

Arrange the array into groups using a distinct identifier

I am utilizing a plugin called https://github.com/yapapaya/jquery-cloneya to generate multiple form inputs as illustrated below: create_order_shirt_shoulder[0] // form name create_order_shirt_chest[0] // form name By duplicating this form container, the ...

Discovering applied styles based on component props in Material-UI v5 using browser developer tools

When working with Material UI v4, I found it easy to identify which styles are applied by component props classname using browser dev tools. This allowed me to override specific styles of the component effortlessly. However, in Material UI v5, I am unsure ...

Adding a class to a navigation item based on the route path can be achieved by following

I am currently working on a Vue.js project and I have a navigation component with multiple router-links within li elements like the example below <li class="m-menu__item m-menu__item--active" aria-haspopup="true" id="da ...

Unlocking the Power of RxJS with Observable Sharing

Let's take a look at a function that contains the code below: private foo() { let obs: Observable<any> = this._http.get<number>('/foo') obs.subscribe(x=> { console.log("foo : " + x) }); this.blah(ob ...

Is it feasible to iterate through a c-array within a function using just a single pointer as a parameter?

Currently, I am experimenting with C programming, where I have created an array and passed it to a function along with its size. This allows me to iterate through the array and print all of its elements. However, I am now interested in achieving the same r ...

What are some methods to manipulate the appearance of text with jquery?

I am having trouble with jQuery and it seems like it's not working properly. Can anyone help me locate the error? My aim is to create a "Read less" button that will show more content when clicked. However, when I click on "Read More", nothing happens. ...

Determine the specific assertions that have caused the protractor test to fail

Is it possible to identify the specific test that failed when a protractor test fails? For instance, if the output only shows: 1 test, 1 assertion, 1 failure When there are multiple assertions and failures, identifying which one failed can be challengin ...

PHP - Attempting to access a property of an invalid object

I'm having trouble iterating through an object property called items, which contains an array: foreach ($this->footerList->items as $item) Despite confirming that $this->footerList indeed contains the items array using var_dump($this-> ...

Guide on updating the URL for the login page in the Next-Auth configuration

I successfully integrated authentication using Next-Auth in my Next.js project. In the index.js file (as per the Next-Auth documentation), I only return a User if there is an active session export default function Home({characters}) { const {data: ses ...

What is the best way to incorporate ngRoute into Jasmine / Karma for testing AngularJS applications?

I am currently working on setting up a basic unit test example. Everything is running smoothly with this app.js: var whapp = angular.module('whapp', []) .filter('reverse', [function(){ return function(string){ return string ...

Prevent the onclick function of a span element from being triggered when the user clicks on a dropdown menu contained within

Just delving into the world of web development and currently tackling a React project. Encountered an issue where I need to make a span element clickable. However, there's a dropdown within that span that doesn't have any onClick event attached t ...