下面的函数做了一个惊人的工作,用一个点标记的字符串来检索深度对象键值:
function getPathValue(obj, path) {
return new Function('_', 'return _.' + path)(obj);
}例如,它使用以下内容作为路径参数返回类似于"bar“的键的值:
'data.abc.foo.bar'但是,一些API将额外字符串JSON打包成一些键值。
我正在寻找对上述函数的增强,以处理这种情况。
例如,Stack自己的WebSocket服务:
wss://qa.sockets.stackexchange.com/返回如下字符串:
{"action":"155-questions-active","data":"{\"siteBaseHostAddress\":\"stackoverflow.com\",\"id\":53819390,\"titleEncodedFancy\":\"Should I start with webGL1 or webGL2 when using Three.js\",\"bodySummary\":\"Spent some time learning and understanding the basics of webGL and I'm now diving into Three.js.\\n\\nI noticed that I have the option of using webGL1 or webGL2. Seems as if webGL1 is the default, however ...\",\"tags\":[\"three.js\",\"webgl\"],\"lastActivityDate\":1545064508,\"url\":\"https://stackoverflow.com/questions/53819390/should-i-start-with-webgl1-or-webgl2-when-using-three-js\",\"ownerUrl\":\"https://stackoverflow.com/users/8226111/romanrogers\",\"ownerDisplayName\":\"romanrogers\",\"apiSiteParameter\":\"stackoverflow\"}"}并且我希望能够使用上面的函数来检索具有如下输入字符串的值:
'data.bodySummary'也许输入字符串可能类似于:
'data/bodySummary'其中solidus (/slash)表示JSON.parse()。
注意,这需要是动态的,因为我希望在一般情况下,最终用户可以选择任意键来返回值。
发布于 2018-12-18 01:44:24
下面是一个函数,它将对象或JSON字符串作为第一个参数,将键路径字符串或数组作为第二个参数,然后使用键路径递归遍历对象。
let object = {"action":"155-questions-active","data":"{\"siteBaseHostAddress\":\"stackoverflow.com\",\"id\":53819390,\"titleEncodedFancy\":\"Should I start with webGL1 or webGL2 when using Three.js\",\"bodySummary\":\"Spent some time learning and understanding the basics of webGL and I'm now diving into Three.js.\\n\\nI noticed that I have the option of using webGL1 or webGL2. Seems as if webGL1 is the default, however ...\",\"tags\":[\"three.js\",\"webgl\"],\"lastActivityDate\":1545064508,\"url\":\"https://stackoverflow.com/questions/53819390/should-i-start-with-webgl1-or-webgl2-when-using-three-js\",\"ownerUrl\":\"https://stackoverflow.com/users/8226111/romanrogers\",\"ownerDisplayName\":\"romanrogers\",\"apiSiteParameter\":\"stackoverflow\"}"};
function asObject(str) {
try {
return JSON.parse(str);
} catch (e) {
return str;
}
}
function valueAtKeyPath(o, path) {
o = asObject(o);
if (typeof path === 'string') path = path.split('.');
if (!o || !path.length) return o;
return valueAtKeyPath(o[path[0]], path.slice(1));
}
console.log(valueAtKeyPath(object, 'action'))
console.log(valueAtKeyPath(object, 'data.id'))
https://stackoverflow.com/questions/53819904
复制相似问题