Getting to a nested key in a JSON object with JavaScript: a step-by-step guide

Currently, I'm working with a JSON file and need to extract the fileName tag for use.

{
"dataset": {
    "private": false,
    "stdyDscr": {
        "citation": {
            "titlStmt": {
                "titl": "Smoke test",
                "IDNo": {
                    "text": "10.5072/FK2/WNCZ16",
                    ".attrs": {
                        "agency": "doi"
                    }
                }
            },
            "rspStmt": {
                "AuthEnty": "Dataverse, Admin"
            },
            "biblCit": "Dataverse, Admin, 2015, \"Smoke test\", http://dx.doi.org/10.5072/FK2/WNCZ16,  Root Dataverse,  V1 [UNF:6:iuFERYJSwTaovVDvwBwsxQ==]"
        }
    },
    "fileDscr": {
        "fileTxt": {
            "fileName": "fearonLaitinData.tab",
            "dimensns": {
                "caseQnty": "6610",
                "varQnty": "69"
            },
            "fileType": "text/tab-separated-values"
        },
        "notes": {
            "text": "UNF:6:K5wLrMhjKoNX7znhVpU8lg==",
            ".attrs": {
                "level": "file",
                "type": "VDC:UNF",
                "subject": "Universal Numeric Fingerprint"
            }
        },
        ".attrs": {
            "ID": "f6"
        }
    }
},

I primarily work with d3.js, along with some parts of jQuery and JavaScript. Currently, I am using the following code:

d3.json(url,function(json){ 

              var jsondata=json;

                   var temp = jsondata.dataset.fileDscr.fileTxt.fileName;
}

I am wondering if there is a way to directly access fileName without going through the entire object structure. This would make it easier to adapt to different JSON files with varying nesting levels.

Answer №1

If you are looking to retrieve a specific value from a JSON data object based on a key, this function can help you achieve that.

let jsonData = {...};
function searchValue(jsonObject, targetKey) {
  if (targetKey in jsonObject) return jsonObject[targetKey];
  else {
    let result;
    for (let key in jsonObject) {
      if (jsonObject[key] && jsonObject[key].constructor === Object) {
        result = searchValue(jsonObject[key], targetKey);
        if (result !== undefined) return result;
      }
    }
  }
}
console.log(searchValue(jsonData, 'desiredKey'));

Answer №2

This code snippet is designed to retrieve all the values associated with a specified key in an object structure and return them as a comma-separated string.

function extractKeyValues(obj, key) {    
    var valueString = "";                                                                                 
        for (var prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                var propValue = obj[prop];                                                                                     
                if(typeof(propValue) == 'object') {
                    console.log(propValue);                                                                                               
                    valueString += extractKeyValues(propValue, key);                                                
                } else {
                    if(prop == key){                                                     
                        valueString = valueString + "," + obj[prop];                                                                     
                    }   
                }
            }
        }   
        return valueString;                         
}
alert(extractKeyValues(data, 'filename').replace(',', ''));

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

Determine the TR id when a button within a TD element is clicked using JavaScript/jQuery

Currently seeking a method to generate a unique identifier for use as a parameter in a JavaScript function. Specifically interested in extracting the id of the first td element if feasible. <tr id='it'><td id="#nameiron">Jason</td ...

When Controller Scope Goes Missing in ng-repeat

Upon glancing at my code, it should be evident that I am a newcomer to the world of Angular. I am currently developing an application that enables users to search for text, queries a database whenever the value in the text input changes, and displays a li ...

Showing information from asynchronous AsyncStorage.getItems in React Native

In my app, users have to validate their success on challenges by clicking a validation button which saves the "key":"value" pair of the challenge using this function: async function validate(challenge_nb) { try { await AsyncStorage.setItem(challenge_n ...

Utilizing AngularJS: Triggering a controller function from a directive

I am currently working on a project with a model named 'user', which includes a controller called 'login' and a directive called 'userMenu'. My goal is to have the userMenu directive utilize the 'login' controller th ...

Upon attempting to utilize Socket.io with Next.JS custom server, the server repeatedly restarts due to the error message "address already in

Every time I attempt to execute the refreshStock() function within an API endpoint /api/seller/deactivate, I encounter the following error: Error: listen EADDRINUSE: address already in use :::3000 at Server.setupListenHandle [as _listen2] (net.js:1318: ...

JavaScript - Issue with For Loop when Finding Symmetric Difference

Here is my solution to a coding challenge on FreeCodeCamp called "Symmetric Difference." I'm puzzled as to why my code is returning 2, 3, 4, 6 instead of the expected 2, 3, 4, 6, 7. function sym(args) { args = Array.from(arguments); var new ...

The arrow icon for selecting input in Material Dashboard React is missing

Source Code View Result Why is the arrow icon not visible when viewing the select like this? I am using "@mui/material": "^5.8.6". Can someone please help me with this? <Box sx={{ width: "auto" }}> <FormControl fullWidth> ...

Exploring JSON object Key names in a LotusScript program using ls.snapps.JSONReader

Similar question: Attempting to access lotusscript json reader Is there a way to iterate through the keys in a JSON object when the keys are unknown beforehand and the object is not an array? { "colorsArray":{ "red":"#f00", "green":"#0f ...

Tips for personalizing the export grid menu in angular-ui-grid?

My grid includes an external "Show Details" option that adds extra columns to the grid when clicked. The problem arises with the options for "Export all data" and "Export visible data," which can be confusing in this scenario. While I understand that "vi ...

Tips for choosing between options in JavaScript and AngularJS

How can I choose the appropriate <select> tag option using JavaScript or AngularJS in the backend? Hint: I receive data from an API service and populate a form for editing. Assuming the gender is currently set as Male in the database, how can I disp ...

Utilizing JQuery to Extract Data from a Nested JSON Array

My API is returning a JSON string with various values that I need to extract using JQuery. "[ ["West Baton Rouge test hello world", "1"], ["LSU Parking \u0026 Transportation Services", "2"], ["demokljafsk", "3"], ["latest", "19"], ...

Is there a way to allow only the block code to shift while keeping the other span tags stationary?

Is it possible to change the text without affecting other span tags in the code? I want to make sure only this specific text is updated. How can I achieve that? var para_values = [ { content: "BRAND " }, { content: "MISSION" } ]; functi ...

Sending Enum flag from WCF to JSON client

Within my C# dll, there exists an Enum that has been defined with the attribute [Flags]: [Flags] [DataContract(Namespace = "MyApp")] public enum MobileNotifications { /// <summary> /// /// </summary> ...

Navigating the path for the script src dynamically with the help of Angular.js and Javascript

I could really use some assistance. I am trying to dynamically set the js/css path name using Angular.js/Javascript/Jquery. Let me explain my code below. <script src="/crm/controller/productController.js" type="text/javascript"></script> Let& ...

A guide on transferring and transforming text data on the server

While I have a basic understanding of php, ajax, and javascript (including jQuery), I am still a beginner and could use some assistance with connecting the dots for this simple task: My goal is to allow the user to input text (for example: "I saw the sun, ...

Is there a way to search through a list and apply filters based on parameters found within a nested object?

I have a list that needs to be filtered based on parameters from advancedSearchFilters, which contains nested objects. The goal is to return a list that matches all or any of the specified parameters. const list = [ { additionalPrices: 0, clien ...

Customizing ESLint configurations for a more productive local development environment

Let's consider an inspiring scenario: I am in the process of coding and need to troubleshoot an issue, so here is a snippet of my code: function foo() { console.log("I'm resorting to printf debugging in 2016"); } However, our build setup in ...

javascript to retrieve data by reducing

Here is the code snippet I am working with: var points = 4; var yModifier = []; for (var i = 0; i <= points; i++) { yModifier.push([]); }; yModifier.forEach( (a, j) => { var start = j; var end = start + points; fo ...

Locating numerous words within a given string

In my quest to identify specific words within a comma-separated log, I have encountered an issue. The current code snippet effectively locates individual words, but struggles to find all three words together in the log. $log = "Left Side Turn, Left Side ...

Embark on a journey through Express.js routes with a unique context

After grappling with this issue for a few days, my brain feels fried and I can't seem to find the most efficient solution. My ultimate goal is to be able to repeat a route journey with new context data at the start. For example: app.get('/test& ...