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

Display a complete calendar with the date picker on a webpage

Currently experimenting with React to build a straightforward application. Admiring the appearance of full calendars from these date pickers (once clicked): Material-UI React-Toolbox Wondering if it's feasible to present the full calendar directly ...

Exporting a VueJS webpage to save as an HTML file on your computer

Scenario: I am working on a project where I need to provide users with the option to download a static export of a webpage that includes VueJS as a JavaScript framework. I attempted to export using filesaver.js and blob with the mimetype text/html, making ...

Routes inoperative as intended

When using a standard expressroute for this login, I have noticed that even if the req.body.password is incorrect, I am still getting redirected to '/login'. router.post('/student/login', (req, res) => { if (req.body.password === ...

Find matches between elements based on their names or alt tags and retrieve the associated data

UPDATED FOR BETTER UNDERSTANDING--- I am managing a blog where I want to link images automatically to products in my store. These links will be based on an array generated by Shopify. While I don't have extensive knowledge of jQuery and JSON, I beli ...

What is preventing me from accessing the JSON return values in my .NET MVC project?

I've been stuck on this seemingly minor issue for hours now. Every time I look at the console, it's showing 500 errors and nothing is coming up in alerts. It appears that the Json() function isn't working as expected. I even tried setting a ...

Cloud Firestore trigger fails to activate Cloud function

I am facing an issue with triggering a Cloud Function using the Cloud Firestore trigger. The function is supposed to perform a full export of my sub collection 'reviews' every time a new document is added to it. Despite deploying the function suc ...

What is the best way to decode a complex JSON in a Flutter application?

I need assistance with parsing a complex JSON in Flutter. Despite trying various methods, I am still unsure about the process. Can someone provide guidance on how to approach this situation? { "message": { "header": { " ...

embed the JSON data from one file into the vacant array within a different file's JSON structure

My goal is to include this block of code from the devices_format.json file: { "devices": [ { "name": "new_elsys", "objects": [ { "name": "ServerRoomTemp", "datapoint_type": "measurement", "coder_fiel ...

Tips for resizing the background to match the font size on a canvas marker in Google Maps

Check out my jsFiddle code below: var marker = new google.maps.Marker({ position: new google.maps.LatLng(-25.363882,131.044922), map: map, title:"Hello World!", icon: CanvasCrear("hola", 15) ...

Leveraging Google Cloud Functions with Next.js (Client-Side Rendering)

Having trouble incorporating firebase cloud functions into my Next.js project, encountering an unfamiliar error. firebase-config.js const firebaseConfig = { apiKey: '~~~', authDomain: '~~', projectId: '~~~', storageBu ...

Ways to dynamically eliminate focus around text inputs

I have created an HTML page and here is the link to it: My main goal is to remove the black border around the text input on this page. The challenge I am facing is that the 'things to do' list is generated dynamically, meaning it is empty when t ...

Add United States as an additional attribute to the countries retrieved from the API

I am working with an API that provides data in a specific format: [ { "id": 12, "acf": { "address": { "city": "Bandar Penawar", "state": "Johor", "country ...

AngularJS ng-repeat is not updating when the state changes

Seeking assistance with an Angular application challenge I'm facing. I have implemented a ng-repeat in my app to display the latest messages stored in an array within a controller named "comunicacion": ng-repeat in comunicacion.html <div class=" ...

Image remains fluid within a static div without resizing

Any assistance would be greatly appreciated. I am currently facing an issue with a fixed div that is floating at the bottom of the screen, serving as ad space for the mobile version of a website. The problem arises when attempting to resize the browser win ...

NPM Messer - the innovative chat tool for Facebook Messenger. Ready to see it in action?

Previously, I had the idea of creating my own Messenger client. However, when I reviewed the documentation, it only provided instructions on how to write a chatbot. Despite this obstacle, I stumbled upon something intriguing - a Messer command line client. ...

"Why does the useEffect in Next.js fire each time I navigate to a new route

Currently, I have implemented a useEffect function within the Layout component. This function is responsible for fetching my userData and storing it in the redux-store. However, I have noticed that this function gets triggered every time there is a route c ...

The challenge of populating information within a Datalist

In my code snippet, I have a JavaScript function that is used to populate a Datalist: function PopulateDropDown(facility) { $.ajax({ url: '/Rentals/Base/GetContactsForFacility?selectedFacility=' + facility, data: { facility: ...

Nested Elements in Java JSON with Jackson

I have a JSON string that contains nested values. It looks something like this: "[{"listed_count":1720,"status":{"retweet_count":78}}]" I am interested in extracting the value of retweet_count. Currently, I am using Jackson to work with this data. The ...

Is it possible to transform multiple input values into a JSON array using PHP?

I am working on a task to convert various input values into a JSON array using PHP. Here is the form structure: <input name="title[]"> <input name="description[]"> <input name="total[]"> This is the desired ...

The server encountered an unexpected error while processing the request, possibly due to a

My JavaScript file includes an interval function that calls the following code: setInterval(function() { $.getJSON('/home/trackUnreadMsgs', function(result) { $.each(result, function(i, field) { var temp = "#messby" + result[i].from; ...