Changing a string into an attribute within a nested JavaScript object

I need help accessing a string "key1.key2" as properties of an object. For instance:

var obj = { key1 : {key2 : "value1", key3 : "value2"}};
var attr_string = "key1.key2";

The variable attr_string represents attributes in a nested object that are connected by periods ("."). This could be at any level of depth, such as "key1.key2.key3.key4..."

My goal is to use something like obj.attr_string to retrieve the value of obj["key1"]["key2"], which would be "value1"

Can you advise me on how to accomplish this?

Answer №1

Shoutout to @dfsq for reminding me about the power of using eval.

Behold, my expectation fulfilled - a straightforward method to assess the string attribute of objects.

let obj = { key1 : {key2 : "value1", key3 : "value2"}};
let attr_string = "key1.key2";

let result = eval("obj."+attr_string);

No need to go through the hassle of splitting the string with "." and looping through it to retrieve the value. With eval, any javascript code statement can be evaluated effortlessly.

Important Note: Despite its functionality, it is crucial to emphasize that eval should be avoided at all costs!!!

Refer to: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_eval!.

Answer №2

Are you looking for this specific solution?

let data = { property1: { nestedPropertyA: 'x', nestedPropertyB: { deepProperty: 'y' } },
    attribute_string = 'property1.nestedPropertyB.deepProperty',

    search = function ( data, string ) {

        let idx = 0,
            array = string.split( '.' );

        if ( array.length ) {
            while ( typeof data === 'object' &&  array[ idx ] in data ) {
                data = data[ array[ idx ] ];
                idx++;
            }
        }

        return data;

    };

search( data, attribute_string ); // Returns 'y'

Answer №3

Transforming @John's response into a versatile function (to be utilized by myself)

function extractNestedValue(obj, attributeString){
    var path = attributeString.split(".");
    for (var index in path){
        obj = obj[path[index]];
    }
    return obj;
}

// see how it performs...
x = {a:{b:{c:"joyful moments"}}};
console.log(extractNestedValue(x, 'a'));
console.log(extractNestedValue(x, 'a.b'));
console.log(extractNestedValue(x, 'a.b.c'));

Answer №4

let selectedObj = currentObject;
const strings = attributeString.split(".");
for (let section in strings)
  selectedObj = selectedObj[section[section]];

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

Adjust the contents of an HTTP POST request body (post parameter) upon activation of the specified POST request

Is there a way to intercept and modify an HTTP Post Request using jQuery or JavaScript before sending it? If so, how can this be achieved? Thank you. ...

Create Vuetify components dynamically through programming

My goal is to dynamically create Vuetify components and insert them into the DOM. I've had success with simple components like v-card or v-dialogue, but I'm running into issues with v-data-tables. To demonstrate the problem, I set up a codesandb ...

transform JSON data into XML format with the help of JavaScript

I need help converting a JSON object to an XML String and I'm struggling to find the right method. I recently came across a jQuery plugin called json2xml on https://gist.github.com/c4milo/3738875 but unfortunately, it does not properly escape the data ...

The login process in Next-auth is currently halted on the /api/auth/providers endpoint when attempting to log in with the

My Next-auth logIn() function appears to be stuck endlessly on /api/auth/providers, as shown in this image. It seems that the async authorize(credentials) part is not being executed at all, as none of the console.log statements are working. /pages/api/au ...

The AJAX callback resulted in the request being aborted and the window location being

I am currently working on implementing a client-side redirect for users who are deemed invalid. The server checks if the user has access to the current page, and if not, it returns {data: 'invalid'}. In the success callback of the ajax call, I va ...

The selector bar in Cypress does not work properly when trying to find the text 'foo' using jQuery

Having trouble with jQuery selectors in my Cypress tests. I often need to use jQuery selectors to locate elements based on text or unique generated numbers instead of using cy.contains(). Any help would be greatly appreciated! https://i.sstatic.net/FjqzJ ...

The process of making a pop-up modal instead of just relying on alerts

Attempting to change from using an alert to a pop-up with a simple if statement, but encountering some issues. Here is the current code: if(values == ''){ $('body').css('cursor','auto'); alert("Blah Blah..." ...

Just a Quick Query About Regular Expressions

I need help removing a specific part from a URL string, which looks like this: http://.....?page=1. I am aware that the code "document.URL.replace("?page=[0-9]", "")" does not work, so I am curious to learn how to accomplish this task correctly. Thank you ...

Leveraging configuration files in AngularJS

I'm working on an Angular application that communicates with a Node.js backend Express application. I am using a config file to store environment variables for my Node app. Here's how I access the config file in my Node app: index.js var port = ...

Firebase functions are giving me a headache with this error message: "TypeError: elements.get is not

Encountering the following error log while executing a firebase function to fetch documents and values from the recentPosts array field. Error: Unknown error status: Error: Unknown error status: TypeError: elements.get is not a function at new HttpsEr ...

Method for testing with Jest

I'm relatively new to Jest and I've been having trouble testing this particular JavaScript method: const parseData = (items) => { const data = []; const itemsCount = items.length; for (let i = 0; i < itemsCount; i += 1) { const el ...

Speed up the opening and closing of a div element on mouse hover

Looking to create a smooth delay for opening and closing a div when mouse hover. Here is the code I have: function show_panel1() { document.getElementById('hoverpanel1').style.display="block"; } function hide_panel1() { document.getElementByI ...

Components loading in Angular result in lat long being undefined in google map integration

I am currently utilizing Ionic-angular AGM. I am facing an issue where I am unable to retrieve my current location when the component loads, as it seems like the component is being fired before the latitude and longitude are ready. How can I make this proc ...

The dropdown list is not getting populated with data retrieved from an HTTP response

My experience with making HTTP calls is limited, and I am facing an issue while trying to populate specific properties of each object into a dropdown. Despite attempting various methods, such as using a for loop, the dropdown remains empty. created(){ a ...

Retrieving a property of an object within an array using JavaScript in AngularJS

Seeking advice on how to calculate the total price of products in an array when working within a callback function. Is there a method similar to myArray.(intheobject).price? Or is there a way to handle callbacks effectively to achieve accurate results? th ...

Using the UI Bootstrap radio button within an ng-repeat loop

I'm attempting to create a series of radio buttons using ui bootstrap (http://angular-ui.github.io/bootstrap/) similar to the example on their website, but utilizing ng-repeat: <div class="btn-group"> <label ng-repeat='option in opt ...

Styling paragraph elements using CSS in JavaScript

I need help applying CSS styling to a paragraph that is being extracted using JavaScript. Here's the current code I have: var info = "<p>" + meeting.summary + "</p>; I attempted to add some styling with the following cod ...

Translating PCRE(PHP) regular expressions into ECMAScript(Javascript) syntax

I have this PCRE Regex that I'm using to validate JSON strings, but now I need to convert it to JavaScript so I can use it for validation in a React application. PCRE Regex - /(?(DEFINE) (?<json>(?>\s*(?&object)\s*|\s* ...

When the state changes, initiate the animation

Currently, I am working with Vue.js and need to animate a navigation menu. My goal is to display two li elements when a user hovers over one of the navigation buttons. At the moment, I have set the data type showActivities to false by default and changed ...

Utilizing Rails for dynamic form validation with AJAX

As someone who is new to jQuery, AJAX, and JavaScript in general, I am facing a challenge with front-end validation for a Rails form that utilizes an ajax call to query the server. The validation works fine when I am debugging, giving enough time for the A ...