Exploring the depth of object fields in Javascript: A guide

When developing my React Native app, I encountered an issue with the navigation function. In developer mode, all arguments passed to the function are outputted to the console. However, when a large store is sent as an argument, it cannot be printed due to a cyclic object reference error caused by the deep structure of the object. To address this, I decided to create a function that will inspect all fields of the object and only output information to the console if the field is deeper than one 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){}

If the object is not deep, the function should return the object itself:

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

For a deep object, the function should return non-deep fields along with a flag indicating the presence of deep fields:

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

I would appreciate any recommendations on the best approach to accomplish this task.

Answer №1

Utilize the combination of Object.entries, map, and verify the type using typeof.

const shallowData = {
  name: "Emily",
  age: 30,
  isStudent: true,
  hobbies: ["reading", "painting"]
};
const deepData = {
  name: "Emily",
  details: {
    address: "123 Main St",
    city: "Los Angeles"
  }
};
function determineDepthOfData(data) {
  return Object.fromEntries(
    Object.entries(data).map(([key, value]) => [
      key,
      typeof value === "object" ? "[DEEP_DATA]" : value
    ])
  );
}

console.log(determineDepthOfData(shallowData));
console.log(determineDepthOfData(deepData));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips to prevent encountering the "The response was not received before the message port closed" error while utilizing the await function in the listener

I'm currently in the process of developing a chrome extension using the node module "chrome-extension-async" and have encountered an issue with utilizing await within the background listener. In my setup, the content.js file sends a message to the ba ...

Check for duplicates within 2 arrays by implementing a filtering process

I am trying to figure out how to compare two arrays to determine if there are any duplicates within them. const result = this.specialRange.filter(d => !dayMonth.includes(d)); What I have attempted so far just returns the entire array back to me, but I ...

Having trouble organizing sequellize results according to fields in the joined table

I am currently working with three sequelize models as outlined below: tags: id tag_name product_tags: id tag_id --> Reference Key 'id' from tags product_id --> Reference Key 'id' from products tag_score products: id name My ob ...

Enhancing Javascript Dialog Box with a Touch of Animation

Collaborating with the incredibly talented Mark Eirich has been an amazing experience. We have been working on revamping a JavaScript dialog box together, and Mark has set up something on JSFiddle that will be incredibly beneficial. However, I am seeking a ...

Issue with Cookie Not Capturing Full Range of Codes

On Page Variable = $lgc_code = '1,2,3,15,23,30'; Cookie = 'lgc_cntl' My cookie holds logic codes for each user to determine which banners or icons should be displayed based on their previous web pages visited. Below is the function ...

What are examples of CPU-intensive tasks, such as sorting and searching, that require significant processing power?

When it comes to defining a CPU intensive task in terms of an algorithm or code rather than a specific use case like video editing, what exactly falls into that category? For instance, is sorting, searching, graph traversal, matrix multiplication conside ...

Display several modal pop ups using AngularJS

I'm currently using AngularJS and I have a requirement where I need to check if a student ID exists in the database when a user clicks a button. If the student ID is found in the database, I want to display #modal1, otherwise show #modal2. Is it achie ...

Using Angular.js to trigger a callback function from a separate controller

Currently in my angular project, I am utilizing Angular.js material. I am trying to display a $mdialog with a custom controller, where the user can modify some data and have those changes applied to my $scope variable. This is an example of what I am doing ...

Utilizing Google Maps API v3 ClientID in Your Application: A Guide for Web Browser Integration

Struggling to integrate Google Map V3 API into a .NET application using a purchased ClientID. The application currently relies on the WebBrowser Control to load HTML content into documentText with the URL set as 'about:blank'. However, the issue ...

Execute an executable file with elevated permissions using Node.js

I'm looking to run an .exe file as an administrator using Node. I attempted the following code, but it's not working: exec('runas /user:Administrator "app.exe"', function(err, data) { console.log(err) ...

Unable to manipulate JQuery lightSlider slides using element index

I've been working on a new page design at this link: The code is still a work in progress, so bear with me as I test out some functions and scripts. At the end of the first section, there are 4 logos that, when clicked, will trigger a modal to pop u ...

The functionality of jQuery's .hide method is not effective in this specific scenario

HTML section <div class="navigation-bar"></div> Jquery & JavaScript section function hideUserDiv(){ $('.ask-user').hide(); } var ask = '<div id="ask-user" style="block;position:absolute;height:auto;bottom:0;top ...

Adjusting the array of buttons with various functions within the Header component

I am looking to create a customizable Header component with different sets of buttons that trigger various functions. For example, on the home page, the buttons could be "visit about page" and "trigger vuex action A", while on the about page they could be ...

Is it possible to impose a different style on an element from another culture?

I am currently developing a themes library along with a demo page. The challenge I'm facing is that the demo page needs to showcase styles from the library without using all of the elements. For instance, consider the following style in an external s ...

Incorporate a fresh button into the Tinymce toolbar using C# programming

I have utilized Tinymce text editor/textarea in my webpage. How can I incorporate an additional button onto the toolbar? For instance, upon clicking the added button, it should prompt a dialog with three textfields: title, age, and gender. Upon filling ou ...

Place an image at the top of the canvas at a specific location

Currently, I am in the process of reconstructing this specific website My approach involves working with React (similar to the aforementioned site) and utilizing the same cropper tool that they have implemented. For cropping, I am incorporating react-imag ...

From Google Assistant to Python Results

Is there a way to control a Bitcraze Crazyflie drone using Google Home? I'm looking to give the command "Drone fly to x3 y4" which will be processed through Firebase and result in the Google Assistant Output: "Flying to x3 y4". Additionally, I need an ...

When json.parse encounters an undefined value at position 1

Currently, I am diving into learning express.js and my latest project involves creating a web app that can convert cryptocurrency to Fiat currency. Things have been progressing smoothly so far, but I've hit a roadblock when attempting to use json.pars ...

Using the Composition API in Vue 3: Guide to invoking a method within the template to retrieve a return value

Within my template, I have implemented the following code snippet: <template> {{ getScope(scope.row, itemIn.field) }} </template> For the Option API section, I've included: methods: { getScope(data, key) { const str ...

Exploring ways to loop through JSON object fields within a React application

There is a JSON representation of different categories and their respective subcategories that looks like this: [ { "category": "Mobiles", "sub": [ { "name": "Apple" }, { ...