0

我的 React Native 应用程序中有一个导航功能,它将以开发人员模式传递给它的所有参数输出到控制台,有时我向参数发送了一个大存储并且它无法输出。得到关于循环对象引用的错误,因为对象很深。因此,我决定创建一个函数来检查对象的所有字段,并依赖它将信息输出到控制台,例如,如果对象字段的深度超过 1 级。

const notDeepObj = {
   name: 'John',
   surname: 'Robert',
   age: 28,
   family: false,
};
const deepObj = {
  name: 'John',
  surname: 'Robert',
  bankAccount: {
    accounts: 2,
    cash: true,
    credit false,
    wasCreated: {
      city: 'New-York',
      date: '12.02.2020.',
    }
  }
}
function checkDepthOfObject(obj){}

在不是深对象的情况下,它必须像这样返回对象本身:

checkDepthOfObject(notDeepObj) 
//it will return:
{
   name: 'John',
   surname: 'Robert',
   age: 28,
   family: false,
};

对于深度对象,它必须返回所有非深度字段并加上对象深度字段的标志:

checkDepthOfObject(notDeepObj) 
//it will return:
{
   name: 'John',
   surname: 'Robert',
   bankAccount: '[DEEP_OBJECT]'
};

你能推荐我最好的方法吗?

4

1 回答 1

1

使用Object.entriesandmap检查typeof值。

const notDeepObj = {
  name: "John",
  surname: "Robert",
  age: 28,
  family: false
};
const deepObj = {
  name: "John",
  surname: "Robert",
  bankAccount: {
    accounts: 2,
    cash: true,
    credit: false,
    wasCreated: {
      city: "New-York",
      date: "12.02.2020."
    }
  }
};
function checkDepthOfObject(obj) {
  return Object.fromEntries(
    Object.entries(obj).map(([key, value]) => [
      key,
      typeof value === "object" ? "[DEEP_OBJECT]" : value
    ])
  );
}

console.log(checkDepthOfObject(notDeepObj));
console.log(checkDepthOfObject(deepObj));

于 2020-03-29T16:31:47.810 回答