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

jqueryajax function returns a boolean value upon completion

Recently, I developed a container method to handle an ajax request: function postRating(formData) { $.ajax({ type: "POST", url: '/api/ratings', data: formData }) .done(function () { return true ...

What is the easiest way to simulate the Ctrl+C key event using jQuery?

I need to programmatically simulate pressing Ctrl+C in order to copy text from a page. My initial attempt looked like this: $('#codetext').click( function() { $("#codetext").trigger({ type: 'keydown', which: 99 }); } Her ...

Encountering an npm error: Directory not found when installing a package that relies on another

Note: Even with the most recent npm and node versions installed, none of the solutions provided in npm install error ENOTDIR have worked for me. My current task involves installing two npm modules that are distributed as .tgz packages on NodeRed. 1. x.tg ...

Transform a div's style when hovering over another div using absolute positioning without repetition

I am facing an issue with multiple divs positioned absolutely on top of a primary div with relative positioning. I want one specific div to change its background-color when hovering over another div within the same parent div. Though I know about ad ...

Execute the function when the form is submitted and show the total of the two values

I am currently working on a straightforward custom module for Drupal 7. This module takes two numeric values and upon submission, displays the sum of these values on the same page. While I have the form set up, it is not yet complete. I am facing some dif ...

Troubleshooting AngularJS binding problem when using ngRepeat to handle Collapse and Expand Caret icon

I am experimenting with implementing collapsible and expandable panels within an ngRepeat loop. Here is my approach: <tbody ng-repeat="item in Items"> <tr data-toggle="collapse" class="accordion-toggle"> <td>{{item.name}}< ...

Displaying Vue v-for data in console.log

One interesting issue arises when printing a list in HTML and checking the output in HTML versus in console.log. It seems that the output is duplicated in the console. After some investigation, I made the following observations: Not showing the product ...

Choose all the items that are visible in the list using Angular

If you have the following ng-repeat: <ul class="list-group"> <ng-user-item ng-repeat="user in users | filter:search" user="user" ng-if="assigned.indexOf(user.id) < 0" ng-click="selectFunction(user);"></ng-use ...

Ensure that Angular resolver holds off until all images are loaded

Is there a way to make the resolver wait for images from the API before displaying the page in Angular? Currently, it displays the page first and then attempts to retrieve the post images. @Injectable() export class DataResolverService implements Resolv ...

Encountering the error `ReferenceError: document is not defined` when trying to deploy a Next.js project on Vercel

I recently worked on a Next JS project and deployed it to Vercel. Initially, everything was running smoothly, so I didn't check the website status for a while. I was just developing it locally and pushing updates to GitHub. However, when I finally rev ...

Vue js for filtering and replacing prohibited words

For this scenario, our objective is to screen the words in our input: <input type="text" class="form-control" placeholder="Write something..." v-model="todoInput""> Below are the restricted words that we aim to substitute in the input "restrict ...

In an AngularJS custom filter function, the error message "keys is not defined" is displayed

As I was reviewing examples in an Angular JS book, I came across a concept that has left me puzzled. It involves the use of custom filters with ng-repeat. Below are the code snippets: <a ng-click="selectCategory()" class="btn btn-block btn-default btn- ...

A see-through object appears only properly when viewed from one specific angle

I am currently working with THREE.js and the WebGL renderer, facing an issue with a self-transparent object in my scene. This object is composed of a single geometry with a basic material that includes a texture and has the transparent: true property enabl ...

Recording a message from an HTML input using NodeJS and socket.io

I am currently working on a project where I want to log user input from an input box to the NodeJS console. For example, if a user types "Hello world" into the input box and clicks "Send message to console", I want it to show up as "Hello world" in the con ...

Issue with electron-vue: Unable to modify Vuex state when using RxJS subscribe

I need help with my code involving two functions in the mutations and two pieces of state const state = { files: [], uploadProgress: 0 } const mutations = { SET_UPLOAD_IMAGE: (state, files) => { state.files = files }, UPLOAD_IMAGE: ( ...

Who is responsible for loading a dependency in npm?

npm list shows all package dependencies from the root directory. Is there a method to do the opposite, such as discovering which paths are including a certain dependency? For instance, running npm paths lodash would display only the paths starting from t ...

Using a JSON file as a variable in JavaScript

Hello there everyone! I am looking to create a multilingual landing page. The idea is to have a language selection dropdown, and when a language is chosen, JavaScript will replace the text with the corresponding translation from a JSON file. However, I a ...

Is it guaranteed that ajax will execute during beforeunload event?

I am developing an HTML5 application and I need to send a disconnect ajax request when the user changes or refreshes the page. Currently, I have implemented this code: window.addEventListener("beforeunload", function(event) { $.ajax({ url: api ...

No content appears on the multi-form component in React

After several attempts at building a multi-step form in React, I initially created a convoluted version using React.Component with numerous condition tests to determine which form to display. Unsatisfied with this approach, I decided to refactor the code f ...

Ensuring form input validity in real-time using jQuery's keyup event

I've been working on a form where the user can fill in an input and press enter to move to the next field. Although I have managed to get the functionality to show the next div, I am facing issues with validation... // Moving to next div on Enter ...