Generate object connection through dot traversal that is in the form of a string

After reaching out to a downstream source, the response received looks something like this:

// for simplicity's sake, let's refer to this variable as resp
{
   "data":{
        "abc": {
            "value":"Hi there",
            "timestamp":"xxxxxxxxxx"
        }
   }
}

My next task is to access resp.data.abc.value, but the challenge lies in doing it dynamically (meaning that the data.abc.value part is sourced from a database)

The logic flow of my program follows these steps:

/*
(a) Initiate a REST call
(b) Receive and store the response in a variable named "resp"
(c) Fetch the dot-separated path from the database
(d) The database outcome will be "data.abc.value" with data type being string
(e) Devise a method to dissect the DB result and apply it to the "resp" variable value
*/

I attempted utilizing .split() and implementing a loop, yet it's becoming convoluted and intricate to grasp.

Answer №1

One way to handle split dot paths is by utilizing the .reduce method. The challenge lies in managing non-existent paths, but this can be overcome by setting a default value.

const getByDotPath = (path = "", object = {}) => {
  return path
    .split(".")
    .reduce((iteratee = {}, p) => iteratee[p], object)
}

const getByDotPath = (path = "", object = {}) => {
  return path
    .split(".")
    .reduce((iteratee = {}, p) => iteratee[p], object)
}

const resp = {
  data: {
    abc: {
      value: "Hello World",
      timestamp: "yyyyyyyyyy",
    },
  },
}

console.log(getByDotPath("data.abc.value", resp))
console.log(getByDotPath("data.abc.value.xyz", resp))

Answer №2

One option is to utilize the `get` function from the lodash library:

const result = _.get(response, "data.xyz.property");

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

Tips for sending an ID to a path link in React Js

Can anyone assist me in setting up a path for a component like this "/products?id=uniqueId" in my React Js Project? The unique id is retrieved from the database and varies depending on the product chosen. Below is an excerpt of my code: CodeSandbox App.j ...

React SlideMenu will not close when a link is clicked

I am facing an issue with my off-canvas menu, which slides in when the variable isOpen is set to true. However, the problem arises when trying to slide it back out upon clicking a Link to navigate to another page. Instead of sliding out, the mobile menu oc ...

What is the significance of curly braces within function parameter declarations in JavaScript?

Recently, I have been exploring a tutorial that delves into setting up React with Redux. While following along, I came across some unfamiliar syntax involving curly braces within function parameter definitions. Can someone explain what purpose these serve? ...

Updating the progress bar without the need to refresh the entire page is

Currently, I have two PHP pages: page.php and loader.php. Loader.php retrieves data from MySQL to populate a progress bar, while page.php contains a function that refreshes loader.php every second. This setup gets the job done, but it's not visually a ...

Update text displayed on radio button selection using jQuery

Is there a way to change the label text on a selected radio button from "Set default" to just "default" using jQuery? I think I need to use the class radio-default as the selector, but I'm not very familiar with jQuery. <div class="radio-default ...

The children's className attribute can impact the parent element

As I work on creating a card object, I envision it with the className .card that is styled in CSS as follows: .card img{position:absolute; width:150px; height:160px} I want only the images inside my div to overlap each other while not affecting the divs ...

Tips for utilizing a variable selector with jQuery's .attr() method

In a jQuery DataTable, there is a scenario where some values can be modified by clicking an edit button. When clicked, a modal popup appears with a form to enter new values for notes and status: ... "columnDefs": [ { ...

How to troubleshoot syntax errors when using the delete function in Three.js within Eclipse

When using the Javascript Library Three.js, it is important to note that the delete keyword can be used as an object property. While this is valid under ECMAScript 5 standards, Eclipse currently only supports ECMA 3. As stated in the Mozilla reference, re ...

"Encountering an issue where ng-repeat doesn't reflect updates after adding a new value to the array. Attempted to use $scope.$

Whenever the chat is opened and a name is clicked, it triggers $scope.openChat(user) which adds a name to the $scope.chat.openChats array. The ng-repeat is supposed to monitor this array for any new values but does not update. I attempted using $scope.$app ...

Is there no body sent in the $.ajax post request?

My server is returning an error when I try to make a simple post request. It's saying that the post request has no body and all the keys have an "undefined" value. Here is the code for my post request: let alert_title = 'Alert'; let alert ...

Having trouble accessing data from the local storage?

const headers = new Headers({ 'access_token' : accToken, 'Content-Type': 'application/json', }); axios.post(baseURI, data, { headers: headers }) ...

Tips for scaling and compressing a canvas image using only pure javascript and HTML5 techniques

I am currently working on resizing and rotating a camera picture on the client side without using any special libraries. I have successfully completed most of the task, but I encounter an offset of 320 pixels when rotating the image. The source of this off ...

How to fix the issue of the mobile Chrome bar occupying part of the screen height in CSS

I am encountering a well-known issue with my collapsible scrollable bar implemented in Bootstrap. The problem occurs when scrolling on mobile devices, as the search bar takes up space from the sidebar's 100% height, causing the scrollbar to not reach ...

What issues are present with the JavaScript event management in this scenario? (Specifically using the click() and hover() jQuery functions)

Currently, I am in the process of developing a proof-of-concept for a project that mimics Firebug's inspector tool. For more detailed information, please refer to this linked question. You can view an example page of my work which has only been teste ...

Creating evenly spaced PHP-generated divs without utilizing flexbox

My goal is to display images randomly from my image file using PHP, which is working fine. However, I am facing an issue with spacing the images evenly to fill the width of my site. This is how it currently appears: https://i.stack.imgur.com/AzKTK.png I ...

What is the process for creating a selector that links to an element that has been dynamically generated?

Can anyone help me figure out how to create a selector that links to a dynamically created element without using an event on the dynamic element? By dynamically created element, I mean an element that is not present in the HTML at the beginning. I know t ...

Having trouble with Angular UI Select functionality?

I have integrated the angular ui select library from https://github.com/angular-ui/ui-select into my project. Instead of using the traditional select element, I am now utilizing the ui-select directive. This is a snippet of my code: <select class=" ...

Revolutionizing user experience: New feature seamlessly triggers button actions with the power of "enter"

I need assistance with modifying a form that contains two buttons and several text inputs. Currently, if the enter key is pressed, it triggers a click event on the first button. However, I want to modify this behavior so that if any of the text boxes are f ...

Attempting to transfer elements from an iteration into a separate array

Currently, I am attempting to insert an associative array into an object that is empty. However, I keep encountering the following error message: An undefined property '#<Object>' cannot be read Here is the code snippet that I am testing: ...

"Learn how to create a scrolling div using a combination of CSS and JavaScript with absolute and relative

After relying solely on "pre-made" components like Mui or TailWind, I decided to create a component using only CSS and maybe JavaScript. However, I encountered some difficulties when attempting to position a div inside an image using relative and absolute ...