How to locate a property within a JSON object using JavaScript

I am facing an issue with a JSON object that resembles the following structure:

{
    name: 'test',
    details: {
        description: 'This is the long description',
        shortDescription: 'This is the short description (ironically longer than the description!)'
    }
}

Even though this example is simplified, the actual object I am working with is more complex. However, to avoid complicating the question, I have left out some details. I have a function in place that attempts to retrieve the value of a specific property within the object. Here is the code snippet:

// Private function for matching fields
var _matchField = function (item, filter) {

    // Variables initialization
    var text = item[filter.field],
        values = filter.expression.split(',');

    // Check if there is any text available
    if (text) {

        // Iterate through the values
        angular.forEach(values, function (value) {

            console.log(text);
            console.log(value);

            // Check for a match
            if (text.toLowerCase().indexOf(value.toLowerCase()) > -1) {

                // Match found
                return true;
            }
        });
    }

    // No matches found
    return false;
}

The problem lies in the line:

var text = item[filter.field],

If the property is simply the name, accessing it using item['name'] works fine with the given object. However, when trying to access the description like item['details.description'], it does not work as expected. I require a function that can take a property name as input and locate the corresponding property within the object to return its value. Before attempting to create one myself, I was hoping to find a straightforward solution that others may have encountered.

Answer №1

If you need a specific function, feel free to create your own

function extractValue(jsonObject, key) {

   if (jsonObject == null || key == null) {
       return null;
   }

   var result = jsonObject;
   var keys = key.split(".");
   for (var index = 0; index < keys.length; index++) {

       result = result[keys[index]];

       if (result == null) {
           return null;
       }
   }

   return result;
}

Take a look at this Plunker demo https://plnkr.co/edit/JTn4hpLoKsWtH1Pm8Z7e?p=preview

Answer №2

To access nested objects or values within an object, you can split the reference and create a function to navigate through the properties.

function retrieveValue(obj, prop) {
    if (typeof prop === 'string') {
        prop = prop.split('.')
    }
    return prop.length ? retrieveValue(obj[prop.shift()], prop) : obj;
}

var data = { name: 'example', content: { description: 'A detailed explanation of something', briefDescription: 'Concise summary' } };

document.write(retrieveValue(data, 'content.description'));

Answer №3

To solve this problem, I devised a solution in the form of a new function:

// Define a private function to retrieve the value of a specified property
var _getPropertyValue = function (object, notation) {

    // Split the notation into individual properties
    var properties = notation.split('.');

    // If there is only one property in the list
    if (properties.length === 1) {

        // Return the value of the single property
        return object[properties];
    }

    // Iterate through each property in the object
    for (var property in object) {

        // Check if the property belongs to the object
        if (object.hasOwnProperty(property)) {

            // If the property matches the first item in the list of properties
            if (property === properties[0]) {

                // Remove the first property from the list
                properties.splice(0, 1);

                // Create a new dot notation based on remaining properties
                var dotNotation = properties.join('.');

                // Recursively find the value using the updated dot notation
                return _getPropertyValue(object[property], dotNotation);
            }
        }
    }
};

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

Retrieving an attribute through the act of clicking a button

How can I retrieve the rel attribute value when clicking on a button with the class selector? <button class="nameClass" rel="relName">Content</button> I am attempting to achieve this by: $(".nameClass").click(function(){ // Here is where ...

When making an asynchronous call, only the initial character is shown in the (HTML) listbox elements

I have a query regarding AngularJS compatibility with IE9. My issue is with a modal window containing a patient list. <div class="modal-header"> <h3 class="modal-title">Patient list</h3> </div> <div class="m ...

The Rsuite Uploader is refusing to transfer the file to the Express server

For my project, I am utilizing an Uploader component from RSuite to upload images to the Express server: <Uploader action={process.env.REACT_APP_API_URL + '/loadMap'} draggable headers={{Authorization: 'Bearer ' + localStorage.getIte ...

Ways to modify color while user moves the screen

I'm working with some jQuery code that changes the colors of elements as the user scrolls down, and I want it to revert back to the original color when scrolling back up. However, the script is not behaving as expected... Here is the original working ...

Errors caused by Typescript transpilation only manifest on the production server

During the process of updating my node version and dependencies on both machines, I came across an issue where building my app in production on one machine resulted in an error, while building it on my main machine did not. I found that the errors disappe ...

The 'errorReason' property is not found within the 'MessageWithMdEnforced' type

I am currently working on a project using meteor, react, and typescript. Here is the section of code that is causing an error: {message?.errorReason && <div>{message?.errorReason}</div> } The error message I am encountering is: "P ...

Is it possible to programmatically set focus on a DOM element using JavaScript or jQuery?

My code dynamically loads select boxes based on user selections. I have a specific instruction to select an option, which looks like this: //returns a string of <option>s by ID $('#subtopic_id').load('ajax.php?f=newSubtopic&am ...

Establishing a Next.js API endpoint at the root level

I have a webpage located at URL root, which has been developed using React. Now, I am looking to create an API endpoint on the root as well. `http://localhost:3000/` > directs to the React page `http://localhost:3000/foo` > leads to the Next API end ...

Set up a global configuration for all $.ajax calls to enable automatic retries in case of a timeout

Looking for a solution to implement a global timeout function using $.ajaxSetup in my Phonegap app. The goal is to automatically retry ajax GET or POST requests in case of timeout, specifically due to poor internet connection. As a Backbone.js user, I hav ...

Ways to manually trigger a reevaluation of Vuelidate validation

Is there a way to trigger Vuelidate to re-check a validation? For example, I have a form field where users can input the name of a remote directory. There is a Vuelidate validation in place that communicates with the server to verify if the directory exis ...

Is it possible to explain why running the same code in Node.js produces different results than in a browser?

When running this code snippet, there is a discrepancy between how it behaves in the browser versus nodeJs. let abc = (() => { function xyz() { this.man = "XYZ" } xyz(); this.man = "ABC"; })() console.log(man); Expected ...

The PHP blocking code in Zend Server not only blocks the response of the current ajax call but also impacts the handling

I encountered a peculiar problem. Suppose I have an ajax call like this; $.ajax({ url:"url1.php", }) Following this ajax call, I have another ajax call as follows; $.ajax({ url:"url2.php", success:function(data){console.log(data);} }) ...

Collapse the active panel on a jQuery accordion with a click event

I'm currently utilizing the Simple jQuery Accordion created by CSS-Tricks, and I am seeking guidance on how to enable the active panel to close when clicking on the link within the dt element. The scenario where I am implementing this is as a menu in ...

Extract JSON data stored as a string within another JSON object

Looking for a more efficient method to deserialize nested JSON objects like this: {"name":"John Doe","age":43,"address":"{\"street\":\"10 Downing Street\",\"city ...

Angular 8: How to Filter an Array of Objects Using Multiple Conditions

I am faced with the following scenario where I need to filter an array of objects based on lineId, subFamily, and status. My current code successfully filters based on lineId, but now I also need to include a condition for subFamilyId. I have two specifi ...

Optimal approach: Utilizing JSON, JQuery, and Codeigniter to organize content within multiple tabs

In the process of developing a calendar list system, I have implemented tabbed dates at the top, with corresponding data listings underneath. While I am comfortable using JSON and JQUERY to load the data into a div, I am uncertain about how to dynamically ...

The initial JavaScript load shared by all users is quite large in the next.js framework

Currently working on a project using the Next.js framework and facing an issue where the First Load JS shared by all pages is quite heavy. I am looking for advice on possible strategies to reduce the weight of the JS file, and also wondering if there ...

Display a Popup at 5PM without the need for a page refresh, updating in real-time

After searching extensively online, I was unable to find a suitable solution for my issue. What I am aiming for is to have a popup appear on my page every day at 5:00 PM without the need to refresh the page. If I happen to access the page before 5:00 PM an ...

Objects that are included into an array will end up with an undefined value

Currently, I am in the process of coding a command for my Discord bot that involves adding items to an array of objects stored within a JSON file. To achieve this functionality, I have implemented the following code snippet: let rawdata = fs.readFileSync(& ...

Unable to execute webdriverIO scripts on Chrome browser with version 108

After updating my Chrome browser to Version 108.0.5359.72, I encountered a problem while running webdriverIO scripts. Despite updating the driver, I kept receiving the following error message: "ERROR webdriver: WebDriver Error: Could not start a new sessio ...