Is it possible to retrieve a value within nested objects using only a single string as the reference?

Can a value inside a nested object be accessed with a single string? For example, consider the object below:

skill: {
    skillDetails: {
        developerDetails: {
            developerName: "mr. developer"
        }
    }
}

Is there a way to retrieve the value using a "JSON path" like this:

skill["skillDetails.developerDetails.developerName"]
?

I am exploring this possibility because I need to pass the key & object into a function (that I cannot modify) which simply returns object[key]

Not certain if this is achievable, hence seeking advice from the community.

Thank you!

Answer №1

To solve this problem without using a built-in method, you can use a simple technique that involves utilizing the split() and reduce() functions. Here's an example:

var user = {
  userDetails: {
    accountDetails: {
      userName: "john_doe"
    }
  }
}

var path = "userDetails.accountDetails.userName";

var result = path
.split('.') // Split the path into individual parts using '.'
.reduce((obj, part) => obj ? obj[part] : undefined, user); // Use reduction to extract the desired value

console.log(result)

Answer №2

Unfortunately, there isn't a straightforward built-in solution for this task. You'll have to create a helper function to get it done.

lodash has a feature to achieve this using the syntax _.get(obj, property).

Here's an example from the documentation:

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');
// → 3

_.get(object, ['a', '0', 'b', 'c']);
// → 3

_.get(object, 'a.b.c', 'default');
// → 'default'

Answer №3

When working with plain JS, the common practice is to utilize Array.reduce as it allows you to traverse the path efficiently to reach the desired value. However, sometimes scenarios involving functions along the path are overlooked. Take a look at this example:

var obj = {
  foo: {
    bar: {
      fooBar: "BARFOO",
      foo: function() { return { c: 'BAR' }}
    }
  }
}

const get = (obj, path) => path.split('.').reduce((r,c) => {
  return r ? typeof r === 'function' ? r()[c] : r[c] : undefined
}, obj)

console.log(get(obj, 'foo.bar.fooBar'))
console.log(get(obj, 'foo.bar.foo'))
console.log(get(obj, 'foo.bar.foo.c'))

Notice that to access the value of foo.bar.foo.c, you have to navigate through a function and execute it. This process can be streamlined by using _.result from lodash:

var obj = {
  foo: {
    bar: {
      fooBar: "BARFOO",
      foo: function() { return { c: 'BAR' }}
    }
  }
}

console.log(_.result(obj, 'foo.bar.fooBar'))
console.log(_.result(obj, 'foo.bar.foo'))
console.log(_.result(obj, 'foo.bar.foo.c'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

It's important to note the difference between _.get, which only retrieves values without traversing through functions, and _.has, which returns a boolean to indicate the validity of the specified path.

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

Unable to store the user's input information in the database

I've been attempting to incorporate an "add" button feature that saves/adds/inserts data into my table. I have inputted some text in the form of tags (input type), but unfortunately, it doesn't seem to be functioning properly. Despite conducting ...

Dynamic rule addition with JQuery Validation

I am searching for a method to dynamically incorporate the jQuery validation rules, as they are needed in various locations. For instance, a user can edit news in two different ways. The first method involves using a standard form with jQuery validation, ...

Updating styled-components variables based on media queries - A step-by-step guide

My current theme setup looks like this: const theme = {color: red}; Within my components, I am utilizing this variable as follows: const Button = styled.button` color: ${props => props.theme.color}; `; I am now faced with the challenge of changin ...

The initial state in NextJS fails to update when routing to the same page with different parameters

This particular project utilizes NextJS The structure of my page's URL is as follows: localhost:3000/first/second When I invoke getInitialProps on this page, the data retrieved from it is passed to the component and used to set the initial state li ...

Import divX from page2 into page 1 by utilizing jsonp to circumvent the restrictions of the same origin policy

I've been attempting to load a div from another page with the following code, $('#result').load('page2.php #divX') However, the JavaScript on that page doesn't seem to work, even though both page1 and page2 are linked to the ...

Error: [Errno 22] occurred while attempting to read a JSON file with .read() method

I'm currently facing an issue while attempting to read a JSON file in Python. The file 'Books_5.json' is located in the Downloads folder, where I am operating from. However, when I try to utilize the .read() function, I encounter the followi ...

Determining When the Collapse Transition in Material UI 5 is Complete

Snippet <Collapse in={expanded} onTransitionEnd={() => console.log('finished')} > <div>foo</div> </Collapse> Error Detection The callback function (onTransitionEnd) is not triggered af ...

React Grid by DevExtreme

Does anyone have a solution for adjusting the fontSize of the TableHeaderRow in a DevExtreme React Grid? Here is some code from a specific website () that I've been exploring: import * as React from 'react'; // Other imports... const Ad ...

Transmitting JSON Web Tokens from AngularJS to Node.js

A situation has arisen where an AngularJS app must pass a JWT to the Node.js instance that is serving it. The Node.js instance has a /user route which will provide a JWT to the Angular client. What specific modifications should be implemented in the exist ...

Concentrate on Selecting Multiple Cells in ag-Grid (Similar to Excel's Click and Drag Feature)

Is there a way to click and drag the mouse to adjust the size of the focus box around specific cells in ag-Grid? This feature is very handy in Excel and I was wondering if it is available in ag-Grid or if there is a workaround. Any insights would be apprec ...

Transforming EJB into a JSON-based web service

I successfully converted EJB 3.1 into a web-service, and now I am looking to create a JSON webservice for better communication with JavaScript components. The JavaScript component will utilize the JSON interface to interact with the system and retrieve nec ...

Mongoose JS is unable to display the query value in the output

Is there a way to use mongoose js to create a collection of kittens with specific attributes like {name: "mike"}? Once this document is created, I need to be able to view its value. I've attempted to write the following code: However, I've enco ...

Preserving the top line or heading while cutting through a table

In my HTML, I have a table with the following structure: <table id="table"> <tr> <td>ID</td> <td>Place</td> <td>Population</td> </t ...

Updating the content of a Telerik RadEditor using Javascript/jQuery

I am currently facing a challenge in manually cleaning the HTML of a Telerik RadEditor using Javascript. Despite my efforts, I am struggling to find the appropriate location to store the value in order for it to be saved during post back. Below is the Jav ...

Permanently remove the span tag and any associated text from the HTML document

Currently, I am working on a project that involves numerous page numbers marked using the span class. Below is an example of this markup: <p>Cillacepro di to tem endelias eaquunto maximint eostrum eos dolorit et laboria estiati buscia ditiatiis il ...

Is there a way to incorporate a fade-in effect when I trigger the expand function in this script?

I recently came across a jQuery plugin for expanding and collapsing content. I am interested in adding a fade-in effect to this plugin specifically when the EXPAND button is clicked. How can I accomplish this? $(document).ready(function () { var maxlines ...

Developing a Multi-Stage Pop-Up with Jquery

I am interested in creating a custom multi-step modal This particular div has dynamically generated classes $('.modal-content').append('<div class="modal-body step step-' + key + '" data-step="'+key+'"></div> ...

What is the best method for transforming a sizable JSON document into XML format?

Looking for advice on how to convert a massive 5.09 GB JSON file to XML format. Online converters have not been able to handle such a large file size. Any recommendations or methods to achieve this conversion? ...

Unable to access the inner object using key-value pair in Angular when working with Firebase

Within my json object, there is an inner object labeled data, containing {count: 9, message: "9 sites synced"} as its contents - also in json format. My objective is to extract the value from message, rather than count. Provided below is the temp ...

I have been utilizing ESBuild to compile JavaScript code for browser usage. However, I encountered an issue when trying to import CSS as I received an error message stating "Unexpected '.'". Can anyone provide guidance on how to resolve this issue?

I am currently developing a JavaScript notebook that operates within the browser environment. To compile my code, I have chosen to utilize ESBuild. My primary objective is to enable the handling of CSS imports such as <import 'bulma/css/bulma.css&a ...