0

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.

jocoders
  • 1,594
  • 2
  • 19
  • 54
  • 1
    `const isDeep = Object.keys(obj).some(key => typeof obj[key] === 'object')` – xdeepakv Mar 29 '20 at 15:38
  • 1
    "*I get the error about the cyclic object reference, because the object is very deep*" - no. The errors stems from trying to output an object with *circular* references, an object that is constructed recursively. It doesn't need to be deep for that. – Bergi Mar 29 '20 at 16:37
  • 1
    Btw, what console are you using? Most do totally fine with circular objects. – Bergi Mar 29 '20 at 16:37
  • 1
    @Bergi i am guessing the OP is using `JSON.stringify` which indeed throws a "**cyclic object value**" error – Gabriele Petrioli Mar 29 '20 at 16:42

1 Answers1

1

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));
Siva K V
  • 10,561
  • 2
  • 16
  • 29