安全地访问Javascript嵌套对象

我有基于json的数据结构,其中包含嵌套对象。为了访问特定的数据元素,我将对对象属性的引用链接在一起。例如:


var a = b.c.d;

如果未定义b或bc,则将失败并显示错误。但是,我想获得一个值,如果它存在,否则就是不确定的。无需检查链中每个值是否存在的最佳方法是什么?


我想使这种方法尽可能通用,所以我不必添加大量的辅助方法,例如:


var a = b.getD();

要么


var a = helpers.getDFromB(b);

我也想尝试避免使用try / catch构造,因为这不是错误,因此使用try / catch似乎放错了位置。那合理吗?


有任何想法吗?


潇潇雨雨
浏览 733回答 3
3回答

FFIVE

您可以创建一个通用方法,该方法基于属性名称数组访问元素,该属性名称数组被解释为通过属性的路径:function getValue(data, path) {&nbsp; &nbsp; var i, len = path.length;&nbsp; &nbsp; for (i = 0; typeof data === 'object' && i < len; ++i) {&nbsp; &nbsp; &nbsp; &nbsp; data = data[path[i]];&nbsp; &nbsp; }&nbsp; &nbsp; return data;}然后,您可以使用以下命令调用它:var a = getValue(b, ["c", "d"]);

三国纷争

标准方法:var a = b && b.c && b.c.d && b.c.d.e;速度非常快,但不太优雅(尤其是具有较长的属性名称)。使用函数遍历JavaScipt对象属性既不高效也不优雅。尝试以下方法:try { var a = b.c.d.e; } catch(e){}如果您确定a以前没有使用过,或者try { var a = b.c.d.e; } catch(e){ a = undefined; }如果您之前已经分配过。这可能比第一种选择更快。

DIEA

获取的价值path的object。如果解析的值为undefined,defaultValue则返回。在ES6中,我们可以从Object下面的类似代码片段中获取嵌套属性。const myObject = {&nbsp; &nbsp; a: {&nbsp; &nbsp; &nbsp; b: {&nbsp; &nbsp; &nbsp; &nbsp; c: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d: 'test'&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; },&nbsp; &nbsp; c: {&nbsp; &nbsp; &nbsp; d: 'Test 2'&nbsp; &nbsp; }&nbsp; },&nbsp; isObject = obj => obj && typeof obj === 'object',&nbsp; hasKey = (obj, key) => key in obj;function nestedObj(obj, property, callback) {&nbsp; return property.split('.').reduce((item, key) => {&nbsp; &nbsp; if (isObject(item) && hasKey(item, key)) {&nbsp; &nbsp; &nbsp; return item[key];&nbsp; &nbsp; }&nbsp; &nbsp; return typeof callback != undefined ? callback : undefined;&nbsp; }, obj);}console.log(nestedObj(myObject, 'a.b.c.d')); //return testconsole.log(nestedObj(myObject, 'a.b.c.d.e')); //return undefinedconsole.log(nestedObj(myObject, 'c.d')); //return Test 2console.log(nestedObj(myObject, 'd.d', false)); //return falseconsole.log(nestedObj(myObject, 'a.b')); //return {"c": {"d": "test"}}
打开App,查看更多内容
随时随地看视频慕课网APP