Leverage recursion for code optimization

I'm currently working on optimizing a function that retrieves JSON data stored in localStorage using dot notation. The get() function provided below is functional, but it feels verbose and limited in its current state.

I believe there's room for improvement by incorporating recursion. Any suggestions on how to refactor this for better efficiency?

get(str) {

  var keys = str.split('.')
  var parent = JSON.parse({"first":{"second":{"third":{"something":"here"}}}})

  if ( keys.length === 1 ) return parent
  if ( keys.length === 2 ) return parent[keys[1]]
  if ( keys.length === 3 ) return parent[keys[1]][keys[2]]
  if ( keys.length === 4 ) return parent[keys[1]][keys[2]][keys[3]]

}

get('first')
get('first.second')
get('first.second.third')

Answer №1

If you're looking for a reliable way to access nested properties, consider using the versatile lodash.get method (check out the documentation). It's a great option.

const get = require('lodash.get');

get('first')
get('first.second')
get('first.second.third')

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

Enhancing the camera functionality of the HTML <input> tag for iPhone and Android devices

I am currently working on a mobile web application that requires access to the device's camera. I am aware that this can be achieved using the following code: <input type="file" accept="image/*" capture="camera" /> The code snippet above suc ...

Adding an exception for ClickAwayListener in React-MUI

Hey there! I'm currently exploring MUI and trying to incorporate the ClickAwayListener API into my project, but I'm facing some difficulties. You can take a look at my project on codesandbox here: https://codesandbox.io/s/react-leaflet-icon-ma ...

Cell values in the array (JSON, Swift 5) represent the quantity of data stored within

I am currently working on fetching multiple values from an array and displaying them in separate cells. Here is the structure of my code: struct SearchResponse: Codable { let ResultSet: ResultSet? } struct ResultSet: Codable { let Result: ...

Updating a data table using POST values in ASP.NET: A step-by-step guide

I am working on updating values in my database and want to ensure that my script is functioning correctly. In order to check, I created a POST method to send the values and confirm they are being received. Now, my question is, once the values are being se ...

Retrieving JSON data using HTTP GET in Flutter

I am struggling with fetching data. As a newcomer to Flutter, I have been trying to resolve this issue despite reading through various articles. While I was able to retrieve the data individually, I faced difficulty in iterating over it using a loop. Below ...

What factors outside of the program could potentially lead to the splice function not functioning as expected?

Within my code, I encountered a peculiar issue involving a splice line along with debug lines on both sides. Take a look: const obj = { x:[1,2], y:{t:"!!!"} } const lenBefore = S.groupings.length const ret = S.groupings.splice(gix, 0, obj) console.log(`${ ...

The art of effectively conveying arguments to the callback function

Here's a react App component that takes in a settingsobj object along with a callback function: export const settingsObj = { handlers: { onClick: (e, dispatch) => { console.log('Click event triggered from settingsObj', e); dispat ...

Battle between Comet and Ajax polling

I'm looking to develop a chat similar to Facebook's chat feature. Using Comet would require more memory to maintain the connection. There seems to be a latency issue when using Ajax polling if requests are sent every 3-4 seconds. Considering t ...

`The logo does not dim when the popup is displayed`

I'm currently experiencing an issue with pop-ups on my page - when they appear, they create a shade over all elements of the page except for my two logos and are displayed with a border around them. Here's what my page looks like before the popu ...

Establish the directive upon receiving the broadcast

Is there a way to trigger a directive when a specific event occurs on the backend and sets a value to false?... This is where the event is being captured .factory('AuthInterceptor', function($q, $injector, $rootScope) { return { ...

Identifying and stopping sluggish third-party JavaScript requests

Our website utilizes various Tracking Pixels to collect data on our visitors. However, at times the third-party JavaScript embedded in our code is waiting for a response from their server. If their server fails to respond properly, it can lead to error mes ...

The serialization of a string with forward slashes / and HTML in NSJSONSerialization is not properly escaped

Having difficulty preventing the string encoding from escaping HTML when converting simple HTML into a string value in a JSON object using NSJSONSerialization. For example, trying to convert basic HTML text: NSString *str = @"<html><body>< ...

Having trouble loading a listbox with JSON data using jQuery

I need help populating a ListBox using jQuery/Json. The code snippet below shows my current approach: jQuery within document.ready: $('#<%=txtSearch.ClientID %>').keyup(function() { if ($('#<%=txtSearch.ClientID %>&apos ...

The touch events are not detected on Pixi.js when buttons are placed on a stage that has been both scaled and

Currently, I am developing a game using pixi js. In order to ensure that the game appears consistent on all screens, I have implemented the following scaling logic: this.scale = Math.max(this.viewWidth, this.viewHeight) / (2048 * this.ratio); Additionall ...

Using jQuery Ajax and PHP to retrieve data from a database based on multiple checkboxes

my code currently only selects one checkbox at a time. What I am trying to achieve is when clicking on the first checkbox, it should display a result. Then, if the second or third checkbox is clicked, all checkboxes should be submitted together to the proc ...

What could be the reason for this code returning a "module not found" error?

Within localbase.js... const fs = require("fs"); if(!fs.existsSync(__dirname + "/localbase.json")) fs.writeFileSync("./localbase.json", "{}"); let database = require("./localbase.json"); The code abov ...

What is the process for determining the vertex position of geometry in three.js after applying translate, rotate, and scale transformations?

I've recently delved into the world of three.js. My current goal involves creating a curve within the scene and subsequently applying some transformations to it. The function responsible for generating the line is showcased below: var random_degree ...

Unraveling complex, nested json structures efficiently with python

After spending countless hours searching through platforms like stackoverflow and geeksforgeeks, I have yet to find a satisfactory solution for my issue. The problem lies in flattening a nested json structure which I've been attempting with tools like ...

What is the best way to prevent an HTML form from being submitted when a user is not logged in, but still allow submission when the user is signed

One of the requirements for users of my application is to be signed in before they can submit form information. Upon clicking on the submit button, my jQuery script verifies if the user is already signed in. If the user is not signed in, an error message ...

Implementing onClick functionality in RecyclerView post JSON data extraction

I recently implemented a RecyclerView in a fragment and successfully parsed JSON data from a website to display it in the RecyclerView following a helpful tutorial found at: Now, my next challenge is adding an onClick listener to the items in the Recycler ...