Enhance and expand an array that is deeply nested within an object

My Data Structure Example:

var tree = {
  name: "docs",
  type: "dir",
  full: "/home/docs",
  children: [
    {
      name: "folder2",
      type: "dir",
      full: "/home/docs/folder2",
      children: [
        {
          name: "file2.txt",
          type: "file",
          full: "/home/docs/folder2/file2.txt"
        }
      ]
    },
    {
      name: "file1.txt",
      type: "file",
      full: "/home/docs/file1.txt"
    }
  ]
}

This specific data structure represents a user's folder contents, and it can vary per user.

A key feature is that each element denotes either a file or directory, where directories have the property type: "dir" and files have type: "file".

If an element is a directory, it will also contain a children property which is an array of similar elements.

Every element has a name property representing its folder or file name, and a full property which is a unique string defining its location in the user's filesystem.

An Algorithm I Developed:

var tree = {
  name: "docs",
  type: "dir",
  full: "/home/docs",
  children: [
    {
      name: "folder2",
      type: "dir",
      full: "/home/docs/folder2",
      children: [
        {
          name: "file2.txt",
          type: "file",
          full: "/home/docs/folder2/file2.txt"
        }
      ]
    },
    {
      name: "file1.txt",
      type: "file",
      full: "/home/docs/file1.txt"
    }
  ]
}

function FindChildrenInTree(fullPath, treeObj) {
    if (treeObj.type != "dir") { return null; }
    if (treeObj.children == null) { return null }
    if (treeObj.full == fullPath) { return treeObj; }

    for (var i = 0; i < treeObj.children.length; i++) {
        if (treeObj.children[i].full == fullPath) {
            return treeObj.children[i];
        } else {
            var result = FindChildrenInTree(fullPath, treeObj.children[i]);
            if (result != null) return result;
        }
    }

    return null;
}

console.log(FindChildrenInTree("/home/docs/folder2", tree))

The algorithm locates a folder in the provided tree object and returns it. Instead of just returning the item found, I aim to add a children property to that item within the given tree.

For instance, with the above tree structure, when providing the algorithm with the item's unique path, the tree, and the array of children I wish to add, I am struggling to figure out how to achieve this. Can you provide any guidance on how to approach this challenge?

Answer №1

Here is an example that may have some issues, but it can give you an idea of how to approach the problem. One way to tackle this is by manipulating bracket notations. Using variable[key], you can access the value whether it's a property name of an object or an index number in an array.

I suggest creating an array with those keys and then iterating through the object using those keys to update the values. Since objects store values by reference, updating one will affect the entire object.

Please bear in mind that English is not my first language, so I hope you can follow along.

// Your code snippet goes here

Answer №2

According to @mhodges, the if statement

(treeObj.full == fullPath) { return treeObj; }
signifies a successful path where the desired item has been found. Any additional logic can be added within this condition, such as
{ treeObj.children = []; return treeObj; }
or any other actions.

Although effective, I'm unsure of how it works as each recursive call seems to modify the passed item rather than the entire tree structure.

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

The JQuery mobile navigation menu effortlessly appears on your screen

I am experiencing an issue with a JQuery mobile navigation that is designed for screens @979 pixels wide. The problem arises when the screen is resized to 979px - the menu pops up fully extended and covers the content of the web page. I suspect that this ...

What is the best way to incorporate a third-party element into Vue using a script tag?

I am in the process of developing a website and I would like to include a widget that links to a podcast on BuzzSprout. Initially, I created the site using HTML to test out different designs, but now I am looking to transition it to VueJS. In my HTML vers ...

Breaking down an array in JavaScript using a variable as the index position

As far as I know, JavaScript arrays can be deconstructed based on a specific index by using the following method. const { 3: selectedByIndex } = arr; This code snippet assigns the value of the element at index 3 to the variable selectedByIndex. But is th ...

Guide on transferring a JavaScript value from Laravel Blade to a controller

Click the button below to initiate the process: <a onclick="myFunction()" href="{{ route('test')}}" data-toggle="tooltip" title="Release Funds" class="datatables__button"><i class=" ...

Looking to find a way to identify strings with hyphens in JavaScript?

I am trying to extract specific parts of a URL that follow a certain pattern like the one below: http://example.com/somepath/this-is-composed-of-hypens-3144/someotherpath Specifically, I am interested in extracting the portion of the URL that consists of ...

Is it possible to perform subtraction between a pointer and a character array?

Currently, I am diving into the world of C programming and exploring the concept of pointers. I came across this code snippet from a tutorial on this site, but I'm struggling to grasp how one can subtract a character array from a pointer. #include< ...

Extract information from JSON using a filter

Is there a way to extract the data value from the list without relying on index positions, considering that the order of arrays can change? I need to specifically target data where code === "size". Unfortunately, the existing structure cannot be ...

Guide on assigning a value to a property within a PHP object

I am looking to update two variables within the Woocommerce cart object. I have inspected the arrays structure within the object using: echo 'Cart Dump: ' . var_dump($woocommerce->session->cart) This output shows: array(1) { ["01822dd92b ...

React: A guide to properly utilizing PropTypes inheritance

I've created a wrapper component for React Router Dom and Material UI: import Button from '@material-ui/core/Button'; import React from 'react'; import { Link as RouterLink } from 'react-router-dom'; const forwardedLink ...

Validation for checkbox completeness is not functioning as expected

I am attempting to create a function that checks if all checkboxes are checked and then changes the class of a button accordingly. However, my code does not seem to be functioning as expected and I am unsure why. <input type="checkbox" id="check1" onch ...

NextJS 12: The dilemma of styled components not rendering server side due to missing CSS

Exciting news with the latest NextJS 12 release - now styled-components is supported without the need for any extra plugins on NextJS! However, I'm running into issues getting it to work with server-side rendering. To activate it, I installed the sty ...

Building a JavaScript application with Node.js and MySQL to seamlessly interact with both offline and online databases

As I develop a JavaScript web-app, my plan is to utilize Node.js for connecting the app with an existing MySQL database. My initial question pertains to the structure of the Node code: should it be written in the same .js file as my application or kept se ...

Receiving an unanticipated value from an array

Actions speak louder than words; I prefer to demonstrate with code: //global variable var siblings = []; var rand = new Date().getTime(); siblings.push('uin_' + rand); alert(siblings['uin_' + rand]); // undefined Why is it coming up ...

Developing an interactive form for instant price calculations

I'm currently tackling a project that involves developing an order form capable of computing the price of a door in real-time. However, I am having trouble deciding on the best approach to take. The form will include the following inputs: Frame (Dr ...

Is it possible for me to add images to the input file individually before submitting them all at once?

When images are inserted one by one, the 'input file' only reads one picture at a time. However, when images are inserted in multiple quantities, the result is displayed for each image that the user inputs. window.onload = function() { //Ch ...

Issue: The system is unable to locate the module titled '@kyleshockey/object-assign-deep'

Recently, I installed the accept-language npm module. When attempting to start my project afterwards, an error message appeared: Error: Cannot find module '@kyleshockey/object-assign-deep' What steps can I take to fix this problem? ...

Determining the decimal power using the position of a for-loop

After selecting a number, the task is to generate circles using d3.js. Each circle will be assigned a color from an array: var color =["red", "blue", "yellow", "orange",.....] ● For instance, if the user picks 593, the first 500 circles should be ...

What could be causing the Universal Code for Disqus to not function properly?

Struggling to get this code to work on my website. I've tried everything, from clearing caches and cookies to disabling plugins and extensions, but still no luck. Check out the code below: import React, { Component } from 'react' import { ...

After reducing the document.domain, the contentWindow of the iframe is met with an Access Denied error

Today, I decided to create an IFRAME dynamically using the following code snippet: var newIframe = document.createElement("iframe"); newIframe.id = 'NewFrame'; newIframe.src = 'NewFrame.html'; document.body.appendChild(newIframe); ...

What tools do Sketchfab and Thangs utilize to display 3D models?

My website functions as a digital library for a particular niche of 3D models. However, I've noticed that the performance on mobile devices when using modelviewer to display glb files is quite poor. Frequently, the page crashes and reloads unexpectedl ...