对深层嵌套对象进行取值&赋值
需求如下:
let obj = { foo: { bar: { name: 'biz' } } }; // 输出 'biz' this.getObj(obj, 'foo.bar.name'); obj = {}; this.getObj(obj, 'foo.bar.name'); // 输出 undefined this.getObj(obj, 'foo.bar.name', 'biz'); // 输出 biz
写出一个符合要求的 getObj(),方法如下:
// getObj 方法 getObj(obj, path, defaultVal) { if (path) { const childArr = path.split('.'); if (childArr.length) { try { console.log('第一步', this.getItem(obj, childArr, 0)); } catch (e) { if (defaultVal !== undefined) { this.setItem(obj, childArr, defaultVal); console.log('第三步', this.getItem(obj, childArr, 0)); } else { console.log('第二步 ', undefined); } } } } }
// 取值方法 方法一: getItem(obj, arr) { let v = ''; arr.reduce((cur, key, index) => { if (index === arr.length - 1) { v = cur[key]; } else { return cur[key]; } }, obj); return v; } 方法二: getItem(obj, arr, index) { if (arr.length - 1 !== index) { const tempObj = obj[arr[index]]; return this.getItem(tempObj, arr, index + 1); } return obj[arr[index]]; }
// 赋值方法 setItem(obj, arr, dv) { arr.reduce((cur, key, index) => { if (!cur[key]) { cur[key] = {}; } if (index === arr.length - 1) { cur[key] = dv; } return cur[key]; }, obj); },