0
我从联机API获取大的嵌套JSON响应。我只需要3个值,但它们是相当嵌套的。我知道每个领域的确切路径。例如,给定:从路径中获取JSON对象的值
obj = {
"result": {
"data": {
"point1": "x",
"value": 2
},
"foo": {
"bar": 7
}
}
}
而且我想路径let p = 'result.data.value'
要能够做到let x = getElement(obj, p);
并有X是2
我写了一个简单的函数(去掉了所有的错误检查,以保持清洁):
const getJSONElement = (data, path) => {
for(let p of path.split('.')) {
data = data[p];
}
return data;
};
它的工作原理,但我觉得我错过了某些东西,或者效率不高。有没有更好的方法来到元素(可能使用Array.reduce
)?
如果导入库是一种选择,我建议selectn:https://github.com/wilmoore/selectn.js。它将适用于你的情况,但也可以处理空检查,数组索引等。 –
或者https://stackoverflow.com/questions/8817394/javascript-get-deep-value-from-object-by-passing-path - 它的字符串或https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key或https://stackoverflow.com/questions/8051975/access-object -child-properties-using-a-dot-notation-string或者https://stackoverflow.com/questions/6393943/convert-javascript-string-in-dot-notation-into-an-object-reference – meagar
Thanks @meagar ,我试着寻找类似的问题,但我想我没有足够好。无论如何,我用'reduce'得到了答案,所以这是一个加号:) –