Using a variable as a key in Javascript to extract the value of a nested object

Suppose I have this object here:

var jsonExample = {  
  "response":{  
    "result":{  
      "status":{
        "name": "Eric"
      }
    }
  }
}

Now I want to dynamically access a nested property:

var jsonKey = "response.result.status.name";
console.log("the status is: " + jsonExample[jsonKey]);  

Can this be achieved somehow?

Answer №1

Accessing a deeply nested property may not be as straightforward as you think. To navigate through the response, you should use the obj[propertyNameAsString] syntax to go step by step.

One approach to achieve this is as follows:

let response = {
  "response": {
    "method": "GetStatus",
    "module": "Module",
    "data": null,
    "result": {
      "status": {
        "name": "Eric"
      },
      "id": 1
    },
    "result_code": {
      "error_code": 0
    }
  }
}

let keyString = "response.result.status.name"
let keyArray = keyString.split('.'); // [ "response", "result", "status", "name" ]
var result = response;

for (key of keyArray) {
  result = result[key]
}

console.log(result)

It is important to note that this method may not handle cases where a string in keyArray does not exist as a property in the preceding object.

Answer №2

To implement this functionality, include the following code:

something['baz'] 

In this case, replace 'baz' with your specific variable that has been transformed into a string. Here is an example using jsonObj:

jsonObj[`${jsonValue}`]

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

Breaking down object properties to 'this' using destructuring in javascript

I would like to set the pagination result from response.data to Vue data. The standard approach would be: this.resultData = response.data.results this.totalResults = response.data.total this.perPageResults = response.data.per_page However, ...

The feature for sending posts in Angular.js appears to be malfunctioning

I have developed a rest-API for adding todos in a MongoDB database. When I use Postman with the setup below, I can successfully save instances: http://localhost:3000/api/addtodo x-www-form-urlencoded with values text="Test", completed: "false". However, ...

error encountered when trying to parse JSON due to an incorrect identifier

While putting together a dbt base model, I encountered an error message as shown below. It seems like there might be a small syntax error at line 6 that I am unable to identify. 15:40:22 Database Error in model base_datacenter_handling_unit (models/l10_st ...

Guide to retrieving a byte array from a server using JavaScript and converting it into a downloadable PDF

I am attempting to convert a byte array received from the server and download it as a pdf. The download functionality is working, but unfortunately, the file appears to be corrupt. My approach involves using JavaScript and vue.js. Function responsible fo ...

What is the best way to send HTML tag content to mark.js and delimit them with a space or comma?

I have been utilizing the mark.js library to highlight keywords on a webpage, and it's been working well. However, I now need to insert an extra space or a comma after each tag such as h1, h2, etc. Initially, I thought about using a loop like the one ...

Node.js with Koa: Discontinuation of generator usage on the next step

I am working with a custom object in which I pass a parameter, and then I need to search for all documents in my collection and process them. Here is the code for my custom object: var db = require('../lib/db'); function Widget(n,l,c,o,t,p) { ...

Vuetify's V-alert component doesn't seem to close properly when the value property is updated, as it only displays the

I have a v-alert component that appears and disappears based on a Vuex store - it shows an error message and clears it after 4s! Below is the code for my V-alert component: The issue I am facing is that the :value attribute does not work when the value o ...

There is an array present with data filled in, but unfortunately, I am unable to retrieve specific elements

As I work on my WordPress 4.7.2 website, I find myself making an AJAX call. The PHP function handling this call returns an array using wp_json_encode(). When I view the data array in the success callback of the AJAX function, everything looks just as expec ...

Loading jsp content into a div dynamically within the same jsp file upon clicking a link

Currently, I am working on creating a user account page. On this page, my goal is to display related JSP pages in a div on the right side when clicking links like 'search user' or 'prepare notes' on the left side. In my initial attempt ...

Initiate magnific popup only when the body class meets certain criteria

I am currently utilizing a plugin called magnific popup and I have a requirement to display a video when a user navigates to the site (while also ensuring it doesn't show every time). To achieve this, I am using localStorage. The code for this functio ...

Tips for real-time content updates on a server-side rendered express application

My social media app, built using Express, Pug, and JavaScript for server-side rendering, is fully functional. However, whenever I comment on a post, I need to manually reload the page to see the new comment displayed. I'm exploring ways to dynamicall ...

What could be causing these strange white lines to show up on my AFrame meshes?

When I import a GLB scene with baked textures into A-Frame using THREE.js, I am experiencing an issue where white lines appear on my objects (pictured below). The walls are grouped meshes which may explain the lines appearing there, but I am puzzled as to ...

Display HTML in JavaScript without altering the Document Object Model

Is it possible to style a custom HTML tag called "location" without directly modifying the DOM? For instance, having <location loc-id="14" address="blah" zipcode="14" /> Would it be feasible to render it like this: <div class="location"> ...

The program is unable to locate the script files I have saved

Currently, I am utilizing node.js alongside express and AngularJS to construct my website. However, I am encountering an issue in the console output where the program seems unable to locate my script files. GET http://localhost:3000/images/entet_gauche.gi ...

Is it possible to render array items into separate divs using the .map() method without displaying commas?

After extensive searching, I have only come across solutions that involve using .join() to combine the items into a single string. const createCard = () => { const pokemonTypes = ['grass', 'fire', 'water']; return ...

What is the process through which Generator.next() works with its parameter?

According to the documentation, it mentions that "You can also provide a parameter to the next method to send a value to the generator." But where exactly does it send this value to? Let's consider these 3 different generator functions: function* fi ...

When multiple AJAX requests are executed simultaneously in PHP Laravel, it may result in a server error related to the 'encryption key'

Could someone assist me with a persistent problem I'm having regarding PHP ajax requests? It has been causing delays in my project for quite some time. If multiple (around 100) ajax GET requests are sent to the PHP controller simultaneously, an error ...

Looking to minimize the amount of HTML code in Angularjs by utilizing ng-repeat

Working with some HTML <tr class="matrix_row" ng-repeat="process in matrixCtrl.processes | filter : { park: parentIndex } track by $index"> <td class="properties" ng-click="dashboardCtrl.currParam=0; dashboardCtrl.currentProcess=process"> ...

The JS slider fails to function properly following the migration of AngularJS from version 1.0.8 to 1.2

Seeking assistance with migrating AngularJS from version 1.0.8 to 1.2 and encountering issues with a JavaScript slider that is no longer functioning post-migration... After upgrading to 1.2, added the angular-route.js library and injected 'ngRoute&ap ...

How can I effectively extract information from this NSString in Objective C?

Exploring the functionalities of the Forecastr wrapper library (https://github.com/iwasrobbed/Forecastr) to extract data from Forecast.io website. In the sample project provided on the github repository, the output displays: { currently = { appare ...