Javasctipt对象层级嵌套太深获取时报错

在Vue.js项目中遇到对象层级嵌套过深导致的获取数据报错问题。解决方案是通过遍历和递归的方式,或者使用lodash库的_.get方法来安全地获取深层属性,避免因路径不存在引发的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对象层级嵌套太深获取时报错

例如

const o = {}
o.b.a.c
// Uncaught TypeError: Cannot read property 'a' of undefined
const d = {b: null }
d.b.a.c
// Uncaught TypeError: Cannot read property 'a' of null

实际业务中在vue的template中,获取后端返回的数据报错

 <div class="report-main-text">
    {{ reportData.examineResult.examineImpression }}
 </div>
解决方案

举例

const object = { a: [{ b: { c: 3 } }] };
const defaultValue = 'defaultValue'
const a = safeGet(object, ["a", "0", "b", "c"], defaultValue )
// val => 3
const b = safeGet(object, ["a", "0", "b", "c", "b"]);
// b=> defaultValue  并且 报错

通过遍历property数组,取相应的值,如果为空就返回错误信息并且采用默认值,如果遍历完整就取相应的值

// a: any
function isArray(a) {
  return Array.isArray(a);
}
function isEmpty(a) {
  return a == null || typeof a !== "object";
}
function throwErrorInfo(obj, state, properties, n) {
  const errorProperty = properties[n];
  const propertiesInfo = properties.join();
  console.error(
    `Cannot read property ${errorProperty} of ${state}`,
    obj,
    properties
  );
}
function safeGet(obj, properties, defaultValue) {
  let state = obj;
  function computeArrayProperties() {
	  for (let i = 0; i < properties.length; i++) {
	      const property = properties[i];
	      if (isEmpty(state)) {
	        throwErrorInfo(obj, state, properties, i);
	        return defaultValue;
	      } else {
	        state = state[property];
	      }
	  }
  }
  if (isArray(properties)) {
    computeArrayProperties()
  }
  return state;
}

利用递归实现,实际就是替换 state , n,逻辑调理清晰

function safeGetByIter(obj, properties, defaultValue = "") {
  const len = properties.length;
  const equal = (x, y) => x === y
  function iterFn(state, n) {
    if (equal(n, len)) {
      return state;
    } else if (isEmpty(state)) {
      throwErrorInfo(obj, state, properties, n);
      return defaultValue;
    } else {
      return iterFn(state[properties[n]], n + 1);
    }
  }
  if (isArray(properties)) {
    return iterFn(obj, 0);
  }
  return defaultValue
}

相关代码

延展

实际在lodash库中,就有相关的解决方案 _.get,文档链接

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值