如何检查 Javascript 中每个对象场的深度
How to check the depth of every object field in Javascript
我在我的 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){}
在对象不深的情况下,它必须 return 对象本身,如下所示:
checkDepthOfObject(notDeepObj)
//it will return:
{
name: 'John',
surname: 'Robert',
age: 28,
family: false,
};
并且在深度对象的情况下,它必须 return 所有非深度字段并加上对象的深度字段的标志:
checkDepthOfObject(notDeepObj)
//it will return:
{
name: 'John',
surname: 'Robert',
bankAccount: '[DEEP_OBJECT]'
};
你能推荐我最好的方法吗?
使用 Object.entries
和 map
并检查 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));
我在我的 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){}
在对象不深的情况下,它必须 return 对象本身,如下所示:
checkDepthOfObject(notDeepObj)
//it will return:
{
name: 'John',
surname: 'Robert',
age: 28,
family: false,
};
并且在深度对象的情况下,它必须 return 所有非深度字段并加上对象的深度字段的标志:
checkDepthOfObject(notDeepObj)
//it will return:
{
name: 'John',
surname: 'Robert',
bankAccount: '[DEEP_OBJECT]'
};
你能推荐我最好的方法吗?
使用 Object.entries
和 map
并检查 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));