Tips on removing properties from an object recursively according to their key/value pairs

My current task involves removing specific children of an object based on whether their "size" key is set to 0.
To achieve this, I am utilizing the npm package directory-tree to generate a JavaScript object representation of a chosen directory.

The structure of the object is as follows:

{
  "path": "directory",
  "name": "directory",
  "children": [
    {
      "path": "directory\\file1.html",
      "name": "file1.html",
      "size": 147,
      "extension": ".html",
      "type": "file"
    },
    ...
  ],
  ...
}

Now, my objective is to recursively delete every directory with a size of 0.

I have attempted to iterate through the object's children using a self-calling function:

function filterObject(obj){
  for(i=0; i<obj.children.length; i++){
    if(obj.children[i].type == "directory"){
      if(obj.children[i].size == 0){
        delete obj.children[i]
      }
      else {
        filterObject(obj.children[i])
      }
    }
  }
}

However, I encountered an error:

renderer.js:22 Uncaught TypeError: Cannot read property 'type' of undefined

When I modified the code to check if each child is an object before proceeding:

if(typeof obj.children[i] === 'object' && obj.children[i].type == "directory"){...}

This adjustment led to a loop issue, causing the browser to freeze and requiring a restart.

Answer №1

One way to handle this situation is by filtering the items and modifying the object for the nested children.

function removeZero(o) {            
    if (o.size === 0) return false;
    if (o.children) o.children = o.children.filter(removeZero);
    return true;
}

var data = { path: "directory", name: "directory", children: [{ path: "directory\file1.html", name: "file1.html", size: 147, extension: ".html", type: "file" }, { path: "directory\file2.htm", name: "file2.htm", size: 147, extension: ".htm", type: "file" }, { path: "directory\file3.php", name: "file3.php", size: 147, extension: ".php", type: "file" }, { path: "directory\\subdirectory-1", name: "subdirectory-1", children: [], size: 0, type: "directory" }, { path: "directory\\subdirectory-2", name: "subdirectory-2", children: [{ path: "directory\\subdirectory-2\\subfile1.html", name: "subfile1.html", size: 147, extension: ".html", type: "file" }, { path: "directory\\subdirectory-2\\subfile2.htm", name: "subfile2.htm", size: 147, extension: ".htm", type: "file" }], size: 294, type: "directory" }, { path: "directory\\subdirectory-3", name: "subdirectory-3", children: [{ path: "directory\\subdirectory-3\\sub-subdirectory", name: "sub-subdirectory", children: [], size: 0, type: "directory" }, { path: "directory\\subdirectory-3\\subfile3.php", name: "subfile3.php", size: 147, extension: ".php", type: "file" }, { path: "directory\\subdirectory-3\\subfile4.html", name: "subfile4.html", size: 147, extension: ".html", type: "file" }], size: 294, type: "directory" }], size: 1029, type: "directory" };

data.children = data.children.filter(removeZero);

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Why does Vue only change a specific array element without updating the DOM?

My curiosity is piqued by a puzzling issue with updating specific items in an array using Vue.js. The documentation cautions that: Due to limitations in JavaScript, Vue cannot detect the following changes to an array: When you directly set an item with th ...

405 error: NGINX blocking POST method in Django DRF Vue.js application

I have encountered a strange issue while building my ecommerce site. Everything seems to be working fine, except for the forms. When attempting to post content, I keep receiving a 405 method get not allowed error. It's confusing as I am trying to use ...

A guide on arranging map entries based on their values

The map displayed below, as represented in the code section, needs to be sorted in ascending order based on its values. I would like to achieve an end result where the map is sorted as depicted in the last section. If you have any suggestions or methods o ...

Tips for personalizing the tooltip on a line chart in Vue.js using Chart.js

Attempting to create a line graph using chart js and vue, but new to both technologies. In the chart below, I am trying to change the tooltip to display "10 Answers July 19, 2023". I have attempted to use the beforeLabel and afterLabel options without succ ...

Error: Unable to simplify version range

Attempting to follow the Express beginner's guide. I created an app and executed npm install as per the provided instructions. > npx express-generator --view=pug myapp > npm install npm ERR! semver.simplifyRange is not a function npm ERR! A com ...

Issue encountered while managing login error messages: http://localhost:3000/auth/login net::ERR_ABORTED 405 (Method Not Allowed)

I am working on the /app/auth/login/route.ts file. import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs' import { cookies } from 'next/headers' import { NextResponse } from 'next/server' export async functi ...

Can a software be created to capture search results from the internet?

Is it feasible to create a program that can extract online search results? I am specifically interested in retrieving data from Some of the data I need include application numbers, such as 9078871 and 10595401 Although there are CAPTCHAs present, I am w ...

What is the most efficient way to perform an inline property check and return a boolean value

Can someone help me with optimizing my TypeScript code for a function I have? function test(obj?: { someProperty: string}) { return obj && obj.someProperty; } Although WebStorm indicates that the return value should be a boolean, the TypeScript compil ...

Guide to creating a nested table with JavaScript

Currently, I am utilizing JavaScript to dynamically generate a table. To better explain my inquiry, here is an example of the HTML: <table id='mainTable'> <tr> <td> Row 1 Cell 1 </td> ...

Refreshing Data on Vuetify Range Slider

My goal is to update the value as the slider position changes. [codepen]https://codepen.io/JakeHenshall/pen/WLezNg <div id="app"> <v-app id="inspire"> <v-card flat color="transparent"> <v-subheader>Tick labels</v-subheade ...

Issue with Browsersync functionality in Docker

My Node.js app is facing an issue with Gulp, Browsersync, and Docker. When I run gulp watch locally, everything functions correctly. However, when I utilize docker-compose up, I encounter an error Cannot GET / The Browsersync UI on port 3001 is operat ...

Ruby on Rails and JSON: Increment a counter with a button press

How can I update a count on my view without refreshing the page when a button is clicked? application.js $(document).on('ajax:success', '.follow-btn-show', function(e){ let data = e.detail[0]; let $el = $(this); let method = this ...

Secure your data with public key encryption and decryption using the Crypto Module in NodeJS

I have a challenge with encrypting/decrypting data using a public key that is stored in a file. The code snippet below illustrates my approach: encryptWithKey (toEncrypt, publicKeyPath) { var publicKey = fs.readFileSync(publicKeyPath, "utf8"); ...

ng-if not functioning properly following the activation of the "Save Changes" button

When I click the edit change button, I am updating information and then hiding the form to show the updated details by clicking on the Save Changes button. My API successfully updates the information, but for some reason, ng-if does not seem to work afte ...

What is the technique for performing asynchronous querying of multiple SQL databases?

Currently, I am in the process of developing a web application using nestjs and typeorm. I have been contemplating the functionality of the following code: const r1 = await this.connection.query(sqlA) const r2 = await this.connection query(sqlB) Does th ...

Tips for fixing the async/await problem in JavaScript

Here is the code I've been working on: let icsFileData = []; icsFileData = filterAttachmentArray.map(async(file) => { let buff = new Buffer(file.data, 'base64'); let text = buff.toString('ascii'); const data = await ical ...

AddThis plugin in Wordpress is unresponsive when used with a theme that relies heavily

I've been struggling to properly set up the AddThis Wordpress plugin to display share buttons below each post in an AJAX theme. After inserting this code into the custom button field on the settings page: <div class="addthis_toolbox addthis_defa ...

Is it possible to dynamically close the parent modal based on input from the child component?

As I follow a tutorial, I am working on importing the stripe function from two js files. The goal is to display my stripe payment in a modal. However, I am unsure how to close the modal once I receive a successful payment message in the child. Below are s ...

Automatically submitting forms without having to refresh the page

I have been searching for answers online, but none of them seem to help me. Additionally, I am struggling to grasp the concept of Ajax. I need everything to happen on a single page without any refreshing until the entire form is submitted. <form id=" ...

Combining Versioning with BundleConfig.cs: A Comprehensive Guide

Encountering a recurring issue where changes made to CSS or Javascript files do not reflect in client browsers unless they manually refresh the page with ctrl+F5. This poses a challenge, especially in a school system with numerous users who may not be awar ...