Javascript 通过点移动创建对象映射,点移动是一个字符串

Javascript 通过点移动创建对象映射,点移动是一个字符串,javascript,Javascript,我给下游打了个电话,收到了类似这样的回复 // for sake of ease, let's call this variable as resp { "data":{ "abc": { "value":"Hi there", "timestamp":"xxxxxxxxxx" } }

我给下游打了个电话,收到了类似这样的回复

// for sake of ease, let's call this variable as resp
{
   "data":{
        "abc": {
            "value":"Hi there",
            "timestamp":"xxxxxxxxxx"
        }
   }
}
然后我需要访问
相应的data.abc.value
,但问题是我必须动态地访问(即
data.abc.value
部分来自数据库)

我的程序流程是这样的:

/*
(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
*/
我尝试过使用
.split()
并迭代一个循环,但它变得非常混乱和复杂,难以理解。

您可以使用lodash的:


对于分割的点路径,可以使用
.reduce
,这里的棘手路径是处理不存在的路径,但可以使用默认值来解决

const getByDotPath = (path = "", object = {}) => {
  return path
    .split(".")
    .reduce((iteratee = {}, p) => iteratee[p], object)
}
const getByDotPath=(path=”“,object={})=>{
返回路径
.拆分(“.”)
.reduce((iteratee={},p)=>iteratee[p],对象)
}
常数响应={
数据:{
abc:{
值:“你好”,
时间戳:“XXXXXXXXX”,
},
},
}
log(getByDotPath(“data.abc.value”,resp))

log(getByDotPath(“data.abc.value.def”,resp))
这不适用于嵌套objects@Alnitak对,更新了答案我不想使用任何外部图书馆请让我试试
const getByDotPath = (path = "", object = {}) => {
  return path
    .split(".")
    .reduce((iteratee = {}, p) => iteratee[p], object)
}