0

I make a call to downstream and receive a response something like

// for sake of ease, let's call this variable as resp
{
   "data":{
        "abc": {
            "value":"Hi there",
            "timestamp":"xxxxxxxxxx"
        }
   }
}

I then need to access resp.data.abc.value but the problem is that I've to do it dynamically (i.e. the data.abc.value part is coming from database)

So the flow of my program is something like this:

/*
(a) Make a REST call
(b) Receive the response, assign it to a variable named "resp"
(c) Grab the dot walking path from db
(d) DB result will be "data.abc.value" and type will be a string
(e) Figure out a way to split the DB result and apply it on the "resp" variablevalue
*/

I've tried using .split() and iterating through a loop but it's getting quite messy and complex to understand.

asprin
  • 9,579
  • 12
  • 66
  • 119

2 Answers2

0

You can use lodash's get:

const data = _.get(resp, "data.abc.value");
domenikk
  • 1,723
  • 1
  • 10
  • 12
0

You could use .reduce for splited dot paths, tricky path here is to handle non-existed path, but it could be solved by using 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: "Hi there",
      timestamp: "xxxxxxxxxx",
    },
  },
}

console.log(getByDotPath("data.abc.value", resp))
console.log(getByDotPath("data.abc.value.def", resp))
hgb123
  • 13,869
  • 3
  • 20
  • 38