Explore the data within nested children using vuejs and javascript in order to display information

I have a treeview folder structure with nested children, including file objects. My goal is to display the details of those files based on the selected node using Vue and JavaScript. Below is the mocked data:

 data:[{
  id: 1,
  name: ‘Project A’,
  type: ‘folder’,
  children: [{
    id: 4,
    name: 'Project A-1’,
    type: ‘folder’,
    files: [
      {
        id: 9,
        pid: 4,
        name: ‘file 3-A’,
        type:’file’,
        description: ‘wifi’,
        country: ‘USA'
      },
      {
        id: 10,
        pid: 4,
        name: ‘file 3-B’,
        type:’file’,
        description: ‘VPN’,
        country: ‘USA'
      }
    ]
  }
  ]
},
{
  id: 2,
  name: 'Services’,
  type: 'folder',
  children:[],
  files: [
    {
      id: 5,
      name: ‘Services-1-A’,
      type:’file’,
      pid: 2,
      description: ‘VPN’,
      country: ‘AUS'
    },
    {
      id: 6,
      name: ‘Services-1-B’,
      type:’file’,
      pid: 2,
      description: ‘WIFI’,
      country: ‘AUS'
    }
  ]
},
{
  id: 3,
  name: 'Servers',
  type: 'folder’,
  children:[],
  files: [
    {
      id: 7,
      name: ‘Servers-1-A’,
      type: ‘file’,
      pid: 3,
      description: ‘VPN’,
      country: ‘CAD'
    },
    {
      id: 8,
      name: ‘Servers-1-B',
      type: ‘file’,
      pid: 3,
      description: ‘WIFI’,
      country: ‘CAD'
    }
  ]
}]

UI CODE:

<el-row style="background: #f2f2f2">
                  <el-col :span="6">
                   <div class="folder-content">
                     <el-tree
                         node-key="id"
                         :data="data"
                         accordion
                         @node-click="nodeclicked"
                         ref="tree"
                         style="background: #f2f2f2"
                         highlight-current
                         >
                         <span class="custom-tree-node" slot-scope="{ node, data }">
                             <span class="icon-folder" v-if="data.type === 'folder'">
                              <i class="el-icon-folder" aria-hidden="true"></i>
                              <span class="icon-folder_text" @click="showFiles(node.id) >{{ data.name }}</span>
                             </span>
                         </span>
                     </el-tree>
                   </div>
                 </el-col>
                 <el-col :span="12"><div class="entry-content">
                  <ul>
                      <li aria-expanded="false" v-for="(file,index) in files" :key="index">
                           <span class="folder__list"><input type="checkbox" :id= "file" :value="file">
                           <i class="el-icon-document" aria-hidden="true"></i>
                          <span class="folder__name">{{file.name}}</span></span>
                     </li>
                 </ul>
                   </div></el-col>
                 <el-col :span="6"><div class="preview_content"></div></el-col>
               </el-row>

method:

    showFiles(id) {
  let f = this.data.filter(dataObject => {
    if (dataObject.children && dataObject.children.id === id) {
      return false
    } else if (!dataObject.children && dataObject.id === id) {
      return false
    }
    return true
  })[1]
  this.files = f.files
  console.log(this.files)
}

My challenge lies in displaying nested files within children when clicking on a specific folder. I attempted filtering the data but could only display root folder files. How can I accurately iterate through and display nested files inside children?

Instead of retrieving file details, I am getting whole node details with prototype.

Any suggestions on how to iterate and display the desired file details?

Answer №1

This code snippet appears to be tailored to your needs. I've included explanations in the comments to help you follow my thought process.

showFiles(id) {
  for (const dataObject of this.data) {
     if (this.dataObject.children && this.dataObject.children.id === id) { // Checking if the file has children and if the child id matches the given id. If so, then these are the files of the nested child.
       this.files = this.dataObject.children.files;
       break;
     }
     if (!this.dataObject.children && this.dataObject.id === id) { // If there are no children in the data object and its id is what we're looking for, then this file belongs to the root folder.
       this.files = this.dataObject.files;
       break;
     }
  }
}

 

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

Contemplating the Sequence of DOM Execution

In the world of html/javascript, the order of execution is typically serial, meaning that the browser reads the code line by line and interprets it accordingly. This is a common practice in most programming languages. Some javascript programmers prefer to ...

JqueryUI Autocomplete functions flawlessly on JSFiddle but fails to work on the actual website

After spending hours working on it, I still can't seem to figure it out. The code functions perfectly on JSFiddle, but not on my own website. Here is the link to the JSFiddle: http://jsfiddle.net/x69chen/sbAR6/16/ I've also included the links ...

The cancel button is experiencing unexpected behavior when used in conjunction with the jQuery load event

I'm experiencing an issue with a cancel button on my website. After clicking the cancel button, it cancels the action but then proceeds to reload the page. I attempted to fix this by adding the "preventDefault" method, but it did not resolve the iss ...

Is there a way to modify the value of an object in a Vuex store using actions in Vue.js?

I have data stored in an array within the state and I need to update a specific object. How can I change the value of the object with id 1 to true using Vuex actions? state.js const array=[] mutations.js storeArray(state, data) { state.array = data ...

How can you ensure that it selects a random number to retrieve items from an array?

I am experiencing an issue with some code I wrote. Instead of displaying a random object from the array as intended, it is showing the random number used to try and display an object. <html> <body> <h1>HTML random objects< ...

What is the method for inputting multi-line strings in the REST Client extension for Visual Studio Code?

Clarification There seems to be some confusion regarding the nature of the data I am storing. I am developing a code snippet web application using Express.js and MongoDB. The purpose is not to store executable code for later use; instead, I am saving snipp ...

Tips for displaying a close icon after completing a file upload

I need to implement a feature where once a user uploads a file, a cross sign should be enabled on the file. I attempted to use javascript for this functionality, but it seems to not be working as expected. There are more than 8-10 different file types that ...

Attempting to access a property from a non-existent object

<?php include 'includes/config.php'; function fetchPages($start, $stop) { // Perform query to retrieve pages between start and stop indexes $query = "SELECT * FROM fanpages WHERE idnum >= $start and idnum <= $stop"; $resul ...

Displaying entries of input data

I have an application that includes a modal window with filters, but I am looking to add another type of filter. However, I am struggling with implementing it in React and would appreciate any help with the code or recommended links. Essentially, I want t ...

Looking for assistance with transferring a JavaScript array to my PHP script

Is there an easier way to transfer a JavaScript array to a PHP file? I've seen examples of using AJAX for this task, but I'm wondering if there's a simpler method. Below is a snippet of the code I'm working with: <html> <hea ...

A system-wide meltdown occurs when attempting to utilize the 'map' property of an undefined element, resulting in a TypeError

Essentially, my goal is to retrieve the techs state from the store code ({ getTechs, tech: {techs, loading}}) => { useEffect(() => { // getTechs(); //eslint-disable-next-line }, []); and utilize it in this section code continuation {!loa ...

The system cannot locate the "default" task. Please consider using the --force option to proceed. The process has been halted due to warnings

Below is the content of my gruntfile.js file var fs = require("fs"), browserify = require("browserify"), pkg = require("./package.json"); module.exports = function(grunt) { grunt.initConfig({ mochaTest: { test: { options: { ...

Is there a method to customize the scrolling speed of VueRouter?

How can I implement smooth scrolling for router links using VueRouter? <router-link :to="{ hash: 'home' }">Home</router-link> <router-link :to="{ hash: 'about' }">About</router-link> Here ...

What distinguishes {key:" "} from {key:" "}, when it comes to JSON files?

I have been working on implementing validation using express Router. The issue I encountered is that when I pass {title:""}, the express-validator does not throw an error. However, when I pass {title:" "}, it works properly. exports.postValidatorCheck = [ ...

Navigating through Node and Express on Azure App Service

I'm facing an issue that I am not sure if it is related to Node or Azure App Service, so here's the situation: In my Node/Express app, I have defined two routes: router.get("/users", checkAuthHeader, userController.getUsers); router.po ...

Trying to populate an array with user input from the console, but every second element ends up getting set as an empty value

I'm encountering an issue while trying to populate an array with console input and then display it in reverse order. For some reason, every other element is being assigned a blank value, resulting in missing lines of input during output. The current a ...

Exploring a 2D array to find the maximum value

I've been working on a code to search for the largest element in a user input array. Take a look at what I have so far: =====main method===== package location; import java.util.Scanner; import java.util.Random; /** * * @author daelynghelardini ...

How to retrieve email input using SweetAlert2 in PHP?

Hello there! I'm curious about the most effective method for integrating PHP with Javascript. My goal is to execute some coding tasks once an email address has been entered. swal({ type: "success", title: "Congrats!", text: "Please enter your P ...

Explaining the defineAsyncComponent Method in Vue 3

Recently, I've been exploring the vue3-beta release and stumbled upon a new feature called defineAsyncComponent. Surprisingly, there's not much information about it online. I'm curious about its use-case and when it should be used. How does ...

Triggering event within the componentDidUpdate lifecycle method

Here is the code snippet that I am working with: handleValidate = (value: string, e: React.ChangeEvent<HTMLTextAreaElement>) => { const { onValueChange } = this.props; const errorMessage = this.validateJsonSchema(value); if (errorMessage == null ...