Show object information in a directory listing format

Struggling with the user interface while trying to replicate the functionality of an S3 bucket. My data is in JSON format:

{"name":"sam's file", "path":"testfile1.jpg"},
{"name":"sam's file", "path":"folder1/testfile2.jpg"},
{"name":"sam's file", "path":"folder1/testfile3.jpg"},
{"name":"sam's file", "path":"folder2/testfile4.jpg"},
{"name":"sam's file", "path":"folder2/testfile5.jpg"},
{"name":"sam's file", "path":"folder2/folder3/testfile6.jpg"},

Trying to use lodash to filter files based on a specified folder (e.g. folder2) and display all filenames within that folder along with any subfolders, excluding files. This will help me create the UI I need.

Expected result: testfile4.jpg, testfile5.jpg and folder3

I also need to distinguish between files and folders for UI presentation purposes. Any simpler solutions or suggestions?

Thanks, Sam

Answer №1

To find the first folder or file that starts with a specific string in the path, you can check if the path starts with the given string and then extract the first coming folder or file.

function extractParts(array, string) {
    return array
        .filter(obj => obj.path.startsWith(string))
        .map(obj => obj.path.match(/\/([^\/]+)/)[1]);
}

var files = [{ name: "sams file", path: "testfile1.jpg" }, { name: "sams file", path: "folder1/testfile2.jpg" }, { name: "sams file", path: "folder1/testfile3.jpg" }, { name: "sams file", path: "folder2/testfile4.jpg" }, { name: "sams file", path: "folder2/testfile5.jpg" }, { name: "sams file", path: "folder2/folder3/testfile6.jpg" }];

console.log(extractParts(files, 'folder2'));

Answer №2

Here is a method to achieve this task:

let arr = [
{"name":"sams file", "path":"testfile1.jpg"},
{"name":"sams file", "path":"folder1/testfile2.jpg"},
{"name":"sams file", "path":"folder1/testfile3.jpg"},
{"name":"sams file", "path":"folder2/testfile4.jpg"},
{"name":"sams file", "path":"folder2/testfile5.jpg"},
{"name":"sams file", "path":"folder2/folder3/testfile6.jpg"}
];

let input_folder = 'folder2';

let result = arr.reduce((a, b) => {
    a['files'] = a['files'] || [];
    a['folders'] = a['folders'] || [];
    let re = new RegExp(input_folder + '\/([^/]+)');
    let matches = b.path.match(re);
    if(matches != null){
        if(matches[1].match(/\./)){
            a['files'].push(matches[1]);
        }
        else {
            a['folders'].push(matches[1]);
        }
    }
    return a;
}, {});

console.log(result);

Answer №3

To extract only the file names from items in the array that have the term folder in their path, you'll need to filter the array first and then map the results to retrieve the file name.

An effective way to do this is by combining the .filter() and .map() methods as shown below:

    var output = files.filter(function(item){
       return item.path.includes("folder2");
    }).map(function(result){
        let regex = new RegExp('folder2\/([^\/]+)');
        let newPath = result.path.replace(regex, '$1');
        return newPath.lastIndexOf("/") > -1 ? newPath.substring(0, newPath.lastIndexOf("/")) : newPath;
    });

Example:

Here's a functional example demonstration:

var files = [{"name":"fileA", "path":"testfile1.jpg"},
{"name":"fileB", "path":"folder1/testfile2.jpg"},
{"name":"fileC", "path":"folder1/testfile3.jpg"},
{"name":"fileD", "path":"folder2/testfile4.jpg"},
{"name":"fileE", "path":"folder2/testfile5.jpg"},
{"name":"fileF", "path":"folder2/folder3/testfile6.jpg"}];


function getFileNamesFromFolder(folderName){
    return files.filter(function(data){
       return data.path.indexOf(folderName) == 0;
    }).map(function(result){
        let regex = new RegExp(folderName+'\/([^\/]+)');
        let newPath = result.path.replace(regex, '$1');
        return newPath.lastIndexOf("/") > -1 ? newPath.substring(0, newPath.lastIndexOf("/")) : newPath;
    });
}

console.log(getFileNamesFromFolder("folder2"));

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

Coordinate Point Visualization in Three.js CameraHelper

Looking to control the rendering volume of a camera in three.js and obtain the control point. You can achieve this by using a camera helper similar to the example provided in the camera example with the pointMap attribute. console.log(cameraOrthoHelper.p ...

Displaying an image gradually as the user moves down the page

Recently, I came across this fascinating website: As you scroll down, the images on the site gradually unveil more details, which caught my attention. This unique effect is not something commonly seen on websites, and I'm curious to learn how it is ...

Setting up initial values for React properties

Below is the React code snippet I am currently working with: this.state = { colsHiddenStatus: new Map([['rowNumber',true], ['id', false], ['firstName', false], ['lastName', false], ['mobile', false], [&a ...

Show the entire phrase within a Bootstrap modal with the help of jQuery, instead of just the initial

I have a PHP script that fetches a name from a database, and I'm using jQuery to display that name as HTML inside a Bootstrap modal when a button is clicked. However, the issue I'm facing is that when the name contains spaces, only the first word ...

Ways to detect the scroll event on a scrollable container?

https://i.sstatic.net/Vx3M7.jpg I am looking to implement a scroll event listener on a specific element, where an arrow icon will appear when the user scrolls up in the message box. Similar to the functionality seen in the Youtube live chat image above. ...

Leveraging highland.js for sequentially executing asynchronous functions while maintaining references to the initial stream data

I am dealing with a series of events: var eventStream = _([{ id: 1, foo: 'bar' }, { id: 2, foo: 'baz' }]); My task is to load an instance of a model for each event in the stream (my Data Access Layer returns promises) and then tri ...

The values returned by a NodeJS script in the Python shell are identical to those returned by Node

The following program was developed to address an issue in another application. In this program, a Python script is called from Node.js to perform a task. The Python script returns results that are then used in Node.js. NodeJS : var pythonShell = require ...

Export Python dictionary to a JSON format file

How can I transfer scraped data into a json file? The data is already in the appropriate format (dictionary, list, string, etc.) #!/usr/bin/python #weather.scraper from bs4 import BeautifulSoup import urllib import json def main(): """weat ...

Steer clear of directly altering a prop within reusable components

I am facing an issue with reusing a custom dropdown that I have created in my component file where props are the value options in the dropdown. When I try to select the dropdown, I get a Vue warning message: [Vue warn]: Avoid mutating a prop directly sinc ...

Error: react-router v4 - browserHistory is not defined

I'm diving into the world of creating my very first React app within Electron (also my first experience with Electron). I have two routes that need to navigate from one to another. Here's the code snippet I am using: Root ReactDOM.render( < ...

GraphQL queries that are strongly-typed

Currently working on a Vue CLI project where I am utilizing axios as my request library. In all the examples I've come across, they use strings for queries like this: { hero { name friends { name } } } Given that I am employing ...

The function $scope.$watch(var,function) was not defined and caused an error stating that

Having trouble with the error message: "undefined is not a function" popping up when attempting to add a watch to the scope. I've been staring at this code for so long now, but still unable to locate the source of the issue. Why am I getting an undef ...

Uncovering data with the power of jQuery: Metadata

Hey there! I have a bunch of divs similar to this: <div class="card {toggle:'A'}"> <div class="card {toggle:'B'}"> <div class="card {toggle:'C'}"> <div class="card {toggle:'D'}"> Right now, ...

Tips on how to engage in a spontaneous audio experience

I am currently developing a Discord bot with the intention of having it play a random mp3 file upon joining a voice channel. case"join": message.delete( {timeout: 5000}) const voiceChannel = message.member.voice.channel ...

The HTTP response object in Express does not provide any data in its return

While working on developing a server using express js, I encountered an issue. When I send a get request to my endpoint from another server, the response is received successfully; however, it does not contain the data that was sent by the server after res. ...

What is the best way to send unprocessed JSON strings to the DeployR WebAPI?

Scenario: Currently, I am dealing with a situation where I have a series of inputs that need to be sent to the deployr server. Among these inputs, some are simple strings while others are JSON strings that are processed by the R script using fromJSON func ...

The mouse pointer adjusts according to the event

I am working on an ajax request and I have implemented a feature where the cursor changes appearance. document.body.style.cursor = "wait"; This immediately shows the cursor as a spinning circle when the request starts. At the end of the request, I ch ...

``Unusual padding for the body in VueJS and Nuxt, with a touch of CSS

I am currently working with VueJS + NuxtJS and have implemented a background gif. Right now, the code looks like this: body { margin: 0 auto; background: url("assets/video/background-darked.gif") no-repeat center center fixed; -webkit-backg ...

Is it possible to read PDF files using Node.js without relying on external libraries?

When I attempt to extract text from a PDF document using Node.js with the fs.readFile method, the response contains strange characters. fs.readFile(directory + '/' + pdf, 'binary', (err, data) => { if (err) { console.l ...

What is the best way to create a jumping animation for an object in Cannon.js and Three.js?

During my quest for a solution, I came across a common practice where users used cannonBody.velocity.y = JUMP_VELOCITY to make an object jump. However, in my scenario, this method only worked while the object was already in motion and not when it was stat ...