JavaScript - Extract specific subvalue from object by using a key string

The issue I am currently encountering in my project involves a complex result object structure, as shown below:

results = {
  a : { b : { c  : value1 }},
  d : value2,
  e : { f : value3 }
  }

I am looking for a dynamic solution to retrieve a specific value based on a string input. For example:

//example 1
const string = '.a.b.c';
const value = results['a']['b']['c']; // = value1
// example 2
const string2 = '.e.f';
const value2 = results['e']['f']; //  = value3

One challenge is that I do not know beforehand how many levels deep the required value will be (direct key, subkey, sub-subkey, etc.).

My initial approach was to split the string and extract the keys into an array:

const keys = string.split('.') // = ['a','b','c']

However, I am struggling to dynamically access the desired value after this step. One possible solution could involve creating if statements to handle different scenarios based on the number of keys present, but I believe there must be a more efficient and cleaner way to tackle this problem. Any suggestions or ideas?

As reference, the if statement approach would look like:

if (keys.length === 1) {
  value = results[keys[0]];
} else if (keys.length === 2) {
  value = results[keys[0]][keys[1]];
} // and so on...

Answer №1

If you want to achieve this, you can utilize the combination of the split and reduce methods.

let data = {
  x : { y : { z : 'result1' }},
  m : 'result2',
  n : { o : 'result3' }
}

function fetchValue(str) {
  return str.split('.').reduce((obj, key) => obj[key], data)
}

console.log(fetchValue('x.y.z'))

console.log(fetchValue('n.o'))

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

What is the best way to outline the specifications for a component?

I am currently working on a TypeScript component. component @customElement("my-component") export class MyComponent extends LitElement { @property({type: String}) myProperty = "" render() { return html`<p>my-component& ...

Tips and tricks for storing and retrieving form state using local storage with jQuery in JavaScript

I'm trying to save the form state in localstorage, I am able to save it successfully but I'm encountering an issue where I am unable to save the input typed data Desired outcome: If I type doggy inside the input box, I want that value to be ret ...

Ways to access device width and height in React without relying on the window object

How can I retrieve the device width or height in React or Next.js without using "window" or "document"? I know that we can achieve this with the useEffect hook to avoid encountering the error: ReferenceError: window is not defined However, using useEffect ...

Could it be true that adding a string with ${class} to Tailwind does not function properly?

Some time ago, I inquired about a way to avoid repeating the same prefix in TailwindCSS like `hover:` multiple times here. Someone was able to solve the issue using javascript, which seems to be working perfectly fine for now. However, a commenter mentio ...

What is the process for adding a class to the last HTML element within an AngularJS ui-select-match element?

I'm having trouble with the angular-js ui-select bootstrap example: edit: Unable to directly link to the plunker, so refer to the fifth (Bootstrap) example on this page: http://angular-ui.github.io/ui-select/ Here's what I don't understan ...

Tips for enhancing the efficiency of a three.js environment within Gatsby.js or react:

I am dealing with a straightforward three.js scene that is rendered using an useEffect hook. The scene loads a model using GLTFLoader(). On the page, there are three event listeners triggered on load. One calculates the browser's inner height, anothe ...

Looking to conceal a JavaScript file or minimize it from the web browser following production build in React

Upon executing the npm run build command using the script provided in my React App's package.json file, "scripts": { "start": "react-scripts start", "build": "set 'GENERATE_SOURCEMAP=false&apos ...

Range Overflow Memory Problem

I'm having an issue with running a macro to copy and paste columns from one worksheet to another. Everything works fine when I only select a few columns, but as soon as I try to copy all the columns I need, I encounter an error. I believe my syntax is ...

What could be causing variations in the performance of my Speech Recognition code each time I run it?

Check out my code snippet: export class voiceRecognition { constructor() { } public startVoiceRecognition() { const recognition = new webkitSpeechRecognition(); recognition.continuous = false; recognition.interimresults = false; recogn ...

Retrieve particular key from document in MongoDB based on provided value

My Document retrieval process looks like this: async findOne(id: string) { return await this.gameModel.findById(id); } async update(id: string, updateGameDto: UpdateGameDto) { const game = await this.findOne(id) // This code snippet prints al ...

How can you determine if a mouseover event is triggered by a touch on a touchscreen device?

Touchscreen touches on modern browsers trigger mouseover events, sometimes causing unwanted behavior when touch and mouse actions are meant to be separate. Is there a way to differentiate between a "real" mouseover event from a moving cursor and one trigg ...

Finding the second through eighth elements in a protractor using a CSS locator

Recently, I have been experimenting with protractor and facing a limitation when trying to reference elements. The only way to refer to them is through CSS, as they only have a class attribute provided. The issue arises when there are more than 7 elements ...

Do you have a solution for resolving the error "TypeError: unsupported operand type(s) for -: 'list' and 'list'" when working with Python?

I'm working on incorporating a Differential Evolution Algorithm to tackle a traveling salesman problem. Unfortunately, I've encountered an error that states: "TypeError: unsupported operand type(s) for -: 'list' and 'list'". I ...

What is the best way to interpret a basic JSON response using jQuery, and how can I send a new

I have developed a WCF service that generates JSON data. I am now looking to create an external website that can interact with this service. Currently, I am running the WCF service over LAN using IIS, allowing me to access the service by navigating to I h ...

Is it possible to modify an input using a specific code?

Is it possible to dynamically change the value of a form input based on specific codes entered in another input without using PHP? For example, when a user enters "HFS73H" into one input, the value of another input changes to "John" - and if a different ...

Stopping an HTTP request and handling errors in Angular

Hi, I need help with canceling my HTTP request after 2 seconds. If no data is received within that time frame, I want it to resolve into the error function and return an empty object. I understand that I need to use the timeout property, but I'm not ...

Exploring the hayfield for 2 possible matches with unique characteristics

I'm working with an array that looks like this: $array = array('one','two','three_num3','four'); as well as a variable which is constantly changing: $term = $_GET['term']; Currently, I'm using t ...

Prevent further execution upon callback in an AJAX request by stopping the click event function

When the function myClick() is called within itself instead of myLoad() on the first click, it leads to double execution of myClick() on the second click. => This results in two consecutive executions of the click event for #myBtn with just one click. ...

Parsing the document to create a list of integers

Looking to extract numbers from a large text file that are separated by commas and store them in a list. The file can be quite extensive, containing thousands of numbers. List<Integer> integerList = new ArrayList<Integer>(); What would be the ...

What is the exact position of Material UI's Grid item?

The CSS grid layout's grid-column property allows for specifying the location of grid items (e.g. grid-column: 1 / 3) I am looking to achieve a similar outcome using Material UI's Grid component, but it seems that I can only determine the number ...