I have a navigation function in my React Native app, that outputs to the console all the arguments passed to it in the developer's mode, and sometimes i sent a big store to the arguments and it can not be output. Get the error about the cyclic object reference, because the object is very deep. Therefore I decided to create a function that will check all the fields of the object and depends on it will output the information to the console, for example if the object filed is deeper than 1 level.
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){}
In the case of not deep object it has to return the object itself like this:
checkDepthOfObject(notDeepObj)
//it will return:
{
name: 'John',
surname: 'Robert',
age: 28,
family: false,
};
And in the case of the deep object it has to return all not deep fields and plus the flag for the deep field of the object:
checkDepthOfObject(notDeepObj)
//it will return:
{
name: 'John',
surname: 'Robert',
bankAccount: '[DEEP_OBJECT]'
};
Can you recommend me please the best way how can I do it.
Use Object.entries
and map
and check for typeof
value.
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));