[Javascript] Safe Nested Object Inspection
JavaScript object nested safe
2023-09-14 08:59:20 时间
A common problem when dealing with some kinds of data is that not every object has the same nested structure. lukeskywalker.parents.father.isjedi works, but anakinskywalker.parents.father.isjedi throws an exception, because anakin_skywalker.parents.father is undefined. But we can reduce a path to provide safe default values and avoid exceptions when walking the same path on non-homogenous objects
let han, anakin, luke; han = { name: 'han', parents: { father: { jedi: true, }, mother: { jedi: false } } }; anakin = { name: 'anakin', parents: { father: { jedi: false, }, mother: { jedi: false } } }; luke = { name: "luke", parents: { mother: { jedi: false } } }; let worries = [ han, anakin, luke ]; function fatherIsJedi(person){ let path = "parents.father.jedi"; return path.split('.').reduce( (acc, curr)=>{ if(acc){ return acc[curr]; } return false; }, person ); }; worries.forEach( (person)=> { console.log(`${person.name}'s fathter is a Jedi: `, fatherIsJedi(person)); })
相关文章
- Javascript中escape()、unescape()、encodeURI()、encodeURIComponent()、decodeURI()、decodeURIComponent()比较
- JavaScript -- 条件语句
- [Javascript] Object.is() vs ===
- [Javascript] Use JavaScript's for-in Loop on Objects with Prototypes
- [Javascript] Required function arguments in Javascript
- [Javascript] Creating an Immutable Object Graph with Immutable.js Map()
- [Javascript] Prototype 2 Object.create()
- Objective-C与JavaScript的交互
- JavaScript Boolean Object 逻辑
- [Javascript] structuredClone - deep clone object
- [Javascript] Keyword 'in' to check prop exists on Object
- [Javascript] Conditionally spread entries to a JavaScript object
- [Javascript] Link to Other Objects through the JavaScript Prototype Chain
- [Javascript] JavaScript赋值时的传值与传址
- [Javascript] Safe Nested Object Inspection
- [ES6] Object.assign (with defaults value object)
- Javascript Mvc学习杂记2
- Javascript网页截屏的方法
- 微信小程序----wx.scanCode(Object object)调起客户端扫码界面进行扫码
- 使用JavaScript调用Microsoft XMLDOM库进行XML字符串的解析
- Atititjs javascript异常处理机制与java异常的转换.js exception process
- 【JavaScript变量】Javascript的全局变量&局部变量
- JSCharting JavaScript 3.3.X 12/17/2022 Crack
- 【JavaScript脚本】——T1基本语法——重点笔记
- IOS Object和javaScript相互调用
- leetcode 斐波那契数列 javascript实现