Minimize the URL length and customize labels for breadcrumb navigation

I am facing an issue where I need to display breadcrumbs with labels in a certain way. Specifically, when clicking on "/bbb" I want it to call "222." Despite my efforts to handle this situation, the output is not correct.

const url = "/aaa/2222/ccc"
const label = "/aaa/bbb/ccc"
breadcrumbs: any;

this.breadcrumbs = url.split('/')
.reduce((acc, cur, i) => {

const url1 = i === 0
? `${acc[i - 1].url1}/${label.split('/')[i]}`
: undefined;

const label1 = i === 0
? `${acc[i - 1].label1}/${url.split('/')[i]}`
: undefined;

const breadcrumb = {
url1,
label1
};
acc.push(breadcrumb);

return acc;
}, []);

var numbers = [175, 50, 25];

The current output displays "/aaa/bbb/ccc/aaa/bbb/ccc/aaa/sites/bbb/ccc/aaa/222". However, I require the UI to show "aaa/bbb/ccc" while the background should be "aaa/222/ccc."

Thank you.

Answer №1

If you are looking to generate an array of objects with label and URL properties, the code snippet below can help accomplish that task.

Simply copy and paste this into your code:

const url = "/example/123/sample"
const label = "/example/abc/sample"

createObject(url, label) {
    const urlArray = url.split("/").slice(1);
    const labelArray = label.split("/").slice(1);
    return urlArray.map((item, index) => {
      return {url: item, label: labelArray[index]}
    })
}

Answer №2

To find the previously accumulated URL/label, ensure that you check if i > 0 and not when i === 0 in your original post.

const url = "/aaa/2222/ccc";
const label = "/aaa/bbb/ccc";

const urlPaths = url.split("/");
const labelPaths = label.split("/");

const snackbar = urlPaths.reduce((acc, urlPath, i) => {
    let path;
    if (i === 0) {
        path = {
            url: "",
            label: "",
        };
    } else {
        const { url, label } = acc[i-1];
        path = {
            url: `${url}/${urlPath}`,
            label: `${label}/${labelPaths[i]}` 
        };
    }

    acc.push(path);
    return acc;
}, []).splice(1);


console.log(snackbar);

Output:

[{
  "url": "/aaa",
  "label": "/aaa"
}, {
  "url": "/aaa/2222",
  "label": "/aaa/bbb"
}, {
  "url": "/aaa/2222/ccc",
  "label": "/aaa/bbb/ccc"
}] 

Note: The trailing .splice(1) call removes the first snackbar path with empty strings for URL/label.

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

Finding the file in a separate directory within the src path

In my projects directory, I have a folder named projects which contains both a game folder and an engine folder. Inside the engine folder, there is an engine.js file. My issue is that I want to access this engine.js file from my game.html file located in a ...

Do not activate hover on the children of parents using triggers

Check out my demonstration here: http://jsfiddle.net/x01heLm2/ I am trying to achieve two goals with this code. Goal number one is to have the mini thumbnail still appear when hovering over the .box element. However, I do not want the hover event to be tr ...

Encountered an error with the POST request - TypeError: Unable to access the 'name' property as it is undefined

I'm currently facing some issues with using nodemailer to send emails. I believe I have everything set up correctly. I came across some posts mentioning deprecated code with the body parser, and I attempted their solutions...I think I've implemen ...

Is it possible to loop through every EventEmitter that is adorned with @Output() in Angular 2?

In order to achieve my goal, I am aiming to iterate through all the EventEmitter instances decorated with @Output within a given component. For example: my-component @Component({ moduleId: module.id, selector: "my-component", templa ...

The issue of the background image not properly zooming and panning alongside the SVG

Having a bit of trouble with my SVG and background image. I've managed to set up zooming and panning for the SVG, but the background image is not cooperating. When I move horizontally, the background image moves along with the SVG, but it doesn't ...

Having trouble extracting a number from an array and encountering a "NaN" error

Encountering an issue with calculating the total grades in the class, as I am receiving an 'NAN' error. Attempted to use parseInt() and .value on students[i].grade but still facing difficulties because of my inexperience. var students= [{name:"D ...

The index.ts file of the CommonJS library being utilized as an external module

Seeking advice on properly developing a reusable commonjs library (npm package). Let's consider the library structure as shown below: —lib ——Helper.ts ——Serialization.ts ——meta ——— Entity.ts —index.ts Each file serves as an ext ...

Erase jQuery from the text

I am struggling with splitting or removing text from a filename. For example, if I have filenames like: 200726100_50-0002.JPG 230514008_60-0001.JPG The desired result should be: 230514008_60.JPG 200726100_50.JPG Am I not using the split function cor ...

Errors occur when iterating through an object in a service with Angular2 Observable

I've scoured the board and numerous websites, but I can't seem to find a resolution to my problem. Although the issue has been previously discussed, none of the solutions seem to work with my code. So here it is; the JSON generated by my middlew ...

Material Design Angular2 Toolbar

I am currently working on designing a toolbar using Material and Angular2. My main challenge is formatting the toolbar in such a way that the search bar appears centered in white, while the "Create Project" button and other buttons are aligned to the right ...

Monitoring changes in the Firebase database using TypeScript

Currently, I am accessing my firebase realtime database through an angular service with the following code: readItems() { return this.af.database.ref(`/path`) .on('value', snap => this.callback(snap.val())); } The callback functi ...

Change the image displayed in a div based on certain conditions dynamically

I am currently developing a website that is solely built using Django. I am interested in having either of two images displayed under a certain condition, similar to the example shown in this VueJs demonstration. Is it achievable without utilizing a front ...

Conceal a dropdown menu when clicked upon

I am currently working on a project that involves a dropdown menu. One of the options triggers an Ajax request to display data in another Div. My goal is to automatically hide the dropdown menu (close it) when this particular option is clicked. <div cl ...

Attempting to display the todo item in the form of <li>, however, the todo.name property is not

I am currently developing a task manager application and have encountered a puzzling issue: When I include the Todo component within the TodoList component and pass the todo item as a prop todo = {name: "ssss", status: false, id: 0.0289828650088 ...

What is the best way to manage multiple write functions triggered by a socket.io room's `emit` event?

Let's start with some context before diving into the question below. Context I am currently developing a browser-based JavaScript game where players join a virtual room and interact by moving tiles. Once the game concludes, user data is sent to the ...

Shifting hues of dots within a grid according to the passing of time

As a newcomer to the world of coding, I have conceptualized an idea for a visually appealing clock. My goal is to visually represent the passage of time throughout the day. To achieve this, I have devised a grid system where each dot on the grid represents ...

Error: Attempting to destructure without initializing / identifier 'name' is already in use [mysql][nodejs]

Whenever I attempt to pass keys as parameters, I'm encountering these errors in nodemon: SyntaxError: Identifier 'name' has already been declared This is the model function causing the issue: const create = async (name, about, site) => { ...

Encountering Issues with Route Query Parameters in Nuxt/Vue Template using TypeScript

I am currently working on a Nuxt.js project with TypeScript and am facing an issue with route query parameters. The specific problem arises when TypeScript throws a type error related to a route query parameter called userType. The issue occurs when I att ...

Do all descendants consistently trigger rerenders?

Recently, I was exploring the React new documentation here, where I came across this interesting piece of information: The context value mentioned here is a JavaScript object with two properties, one being a function. Whenever MyApp re-renders (for examp ...

What is the reason behind having to refresh the page or switch to another tab for the field to display?

Currently, I am in the final stages of completing my update form. However, I am facing an issue with the conditional field. The select field should display a conditional field based on the selected value. The problem I'm encountering is that I need to ...