Iteratively sift through data for boolean value

My navigation dynamically retrieves routes from the vue-router, eliminating the need for manual addition.

Within these routes, there is a boolean key named "inMenu" in both parent and child routes. I have successfully filtered out the parent routes based on this key, but struggling to do the same for the child routes.

var res = this.$router.options.routes.filter(function f(o) {
  if (o.route.meta.inMenu === true) return true

  if (o.children) {
    return (o.children = o.children.filter(f)).length
  }
})

Although I've managed to filter the parent routes using the above code snippet, I'm facing difficulties applying the same logic to filter out the children.

return this.$router.options.routes.filter(route => route.meta.inMenu === true);

Here is some example data to illustrate the structure:

{
  "path": "/orders",
  "component": {
    "name": "Orders",
    "__file": "src/views/Orders.vue",
  },
  "meta": {
    "icon": "fa-history",
    "title": "Abwicklungen",
    "inMenu": true
  },
  "children": [
    {
      "path": "list",
      "name": "orderList",
      "component": {
        "name": "OrderList",
        "__file": "src/views/orders/list.vue",
      },
      "meta": {
        "title": "Bestellliste",
        "icon": "fa-circle-o",
        "inMenu": true
      }
    },
    {
      "path": "details/:id",
      "name": "orderDetails",
      "component": {
        "name": "OrderDetails",
        "__file": "src/views/orders/details.vue"
      },
      "meta": {
        "title": "Bestellung",
        "icon": "fa-circle-o",
        "inMenu": false
      }
    },
    {
      "path": "dailyclosing",
      "component": {
        "name": "OrderList",
        "__file": "src/views/orders/list.vue",
      },
      "meta": {
        "title": "Tagesabschluss",
        "icon": "fa-check",
        "inMenu": true
      }
    }
  ]
}

I aim to hide any route or its children with the "inMenu" key set to false.

Answer №1

To retrieve all objects with a true inMenu property, you can create a new array containing only those objects. Any branches without any items with true for the inMenu property are removed from the result.

function filter(array) {
    return array.reduce((r, { children = [], ...o }) => {
        children = filter(children);
        if (o.meta.inMenu || children.length) r.push(Object.assign({}, o, children.length && { children }));
        return r;
    }, [])
}

var data = [{ path: "/orders", meta: { icon: "fa-history", title: "Abwicklungen", inMenu: true }, children: [{ path: "list", name: "orderList", meta: { title: "Bestellliste", icon: "fa-circle-o", inMenu: true } }, { path: "details/:id", name: "orderDetails", meta: { title: "Bestellung", icon: "fa-circle-o", inMenu: false } }, { path: "dailyclosing", meta: { title: "Tagesabschluss", icon: "fa-check", inMenu: true } }] }, { path: "/orders", meta: { icon: "fa-history", title: "Abwicklungen", inMenu: false }, children: [{ path: "list", name: "orderList", meta: { title: "Bestellliste", icon: "fa-circle-o", inMenu: true } }, { path: "details/:id", name: "orderDetails", meta: { title: "Bestellung", icon: "fa-circle-o", inMenu: false } }, { path: "dailyclosing", meta: { title: "Tagesabschluss", icon: "fa-check", inMenu: true } }] }],
    result = filter(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

I will assume the following:

  1. There are multiple path objects stored in an array.
  2. Each path object has a main meta key at the root level and a children key.
  3. If the value of the root meta key 'inMenu' is false, we remove the entire object along with its children.
  4. The children do not have any nested children of their own.

Our approach involves using the reduce method on the array to check if the 'inMenu' property of each object is true. If it is true, we reconstruct the object while filtering out its children based on a helper function.

var data = [{"path":"/orders","component":{"name":"Orders","__file":"src/views/Orders.vue",},"meta":{"icon":"fa-history","title":"Abwicklungen","inMenu":!0},"children":[{"path":"list","name":"orderList","component":{"name":"OrderList","__file":"src/views/orders/list.vue",},"meta":{"title":"Bestellliste","icon":"fa-circle-o","inMenu":!0}},{"path":"details/:id","name":"orderDetails","component":{"name":"OrderDetails","__file":"src/views/orders/details.vue"},"meta":{"title":"Bestellung","icon":"fa-circle-o","inMenu":!1}},{"path":"dailyclosing","component":{"name":"OrderList","__file":"src/views/orders/list.vue",},"meta":{"title":"Tagesabschluss","icon":"fa-check","inMenu":!0}}]}];

const filterByInMenu = arr => arr.filter(obj => obj.meta.inMenu);

let result = data.reduce((acc, curr) => {
  if (curr.meta.inMenu) {
    acc.push({...curr, children: filterByInMenu(curr.children)});
  }
  return acc;
}, []);

console.log(result);

Answer №3

Take a look at this functional snippet that may help you troubleshoot your code. It seems like you just need to make some adjustments in order for it to work correctly. Vue.js routes are not utilized in this example, but it serves as a guide for updating your function according to your requirements. By studying this snippet, you should be able to identify what needs fixing in your current function.

var data = [{
  "path": "/orders",
  "component": {
    "name": "Orders",
    "__file": "src/views/Orders.vue",
  },
  "meta": {
    "icon": "fa-history",
    "title": "Abwicklungen",
    "inMenu": true
  },
  "children": [
    {
      "path": "list",
      "name": "orderList",
      "component": {
        "name": "OrderList",
        "__file": "src/views/orders/list.vue",
      },
      "meta": {
        "title": "Bestelliste",
        "icon": "fa-circle-o",
        "inMenu": true
      }
    },
    {
      "path": "details/:id",
      "name": "orderDetails",
      "component": {
        "name": "OrderDetails",
        "__file": "src/views/orders/details.vue"
      },
      "meta": {
        "title": "Bestellung",
        "icon": "fa-circle-o",
        "inMenu": false
      }
    },
    {
      "path": "dailyclosing",
      "component": {
        "name": "OrderList",
        "__file": "src/views/orders/list.vue",
      },
      "meta": {
        "title": "Tagesabschluss",
        "icon": "fa-check",
        "inMenu": true
      }
    }
  ]
}];


var res = data.filter(function f(o) {
  if (o.children) {
    return (o.children = o.children.filter(f)).length
  }
  if (o.meta.inMenu === true) return true;
  return false;
})

console.log(res);

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

What is the best way to update an object within a deeply nested array of objects using lodash?

I am facing a challenge in my React JS application where I have an array of objects that I need to dynamically modify. Here is the structure of my array : sections: [ { id: 'e9904688-fd8a-476d-8f46-930bc4d888d1', ...

Error message indicating that an image cannot be located within assets folder while using @error in Nuxt

Having an issue with one of the images in my card component not loading due to a (HTTP Status: 403) error. I wanted to replace it with a default image, so after some research, I found out that I can use @error. <div class="card-thumbnail"> ...

Having trouble getting the Bootstrap tooltip to work on a Select option?

Is there a way to have a tooltip displayed for each option in the select box? <select ng-model="rightList" class="form-control" size="13" multiple> <option ng-repeat="item in selectedList" value="{{$ ...

choose among various options in Javascript

I'm currently using PHP and AJAX to create a basic CRUD system. I want to display a form with three buttons: Grabar, Modificar, and Eliminar. The issue I'm facing is determining the action to take based on which button is clicked. For instance, c ...

Don't initialize each variable within the constructor of a class, find a more efficient approach

I have a collection of JavaScript classes representing different models for my database. Each model contains attributes such as name, email, and password. Is there a more efficient way to create a new User instance without manually assigning values to ea ...

Chaining inheritance through Object.create

Recently, I decided to experiment with Object.create() instead of using new. How can I achieve multiple inheritance in JavaScript, for example classA -> classA's parent -> classA's parent's parent, and so on? For instance: var test = ...

Preventing all hammer.js (angular-hammer) interactions except for single taps

Utilizing the angular-hammer module in my app, I am keen on refining its performance specifically for the tap event. Given that no other gestures are required, I aim to enhance efficiency by excluding unnecessary listening functions, such as double tap. As ...

Guide to fixing Vue app crashes caused by Web Sockets error

I'm encountering an issue with my Vue application as I am unable to load a specific page due to the app crashing. The console displays the following error, even though there is no implementation of Web Sockets in the app. Despite adding this snippet ...

What is the process of calculating the difference between two time values in PHP?

I have searched everywhere online and tried multiple methods over the past couple of days, but still can't seem to achieve the desired result. My goal is to subtract two different times, for example 22:00:00 - 00:30:00 = 21:30:00 $hourToEatLastMeal = ...

What is the correct way to extract results from an Array of Objects in Typescript after parsing a JSON string into a JSON object? I need help troubleshooting my code

Here is my code for extracting data from an array of objects after converting it from a JSON string to a JSON object. export class FourColumnResults { constructor(private column1: string, private column2: string, private column3: string, priv ...

Unable to interact with web element using JavaScript

Struggling to find a solution for simulating a click on a button element on Outlook.com mobile website using JavaScript. Despite numerous attempts from online sources, the button remains unresponsive to clicks. An interesting discovery was made that the c ...

Trouble confirming the password field with regular expressions in angular.js

I'm trying to validate my password field with specific special characters requirements. The field must contain at least one number, upper case letter, lower case letter, and an underscore, all of which are mandatory. I have attempted to achieve this u ...

Typing into the styled M-UI TextFields feels like a never-ending task when I use onChange to gather input field data in a React project

Having an issue where entering text into textfields is incredibly slow, taking around 2 seconds for each character to appear in the console. I attempted using React.memo and useCallback without success :/ Below is my code snippet: const [userData, setUserD ...

Using the information selected from the dropdown menu, the table was refined through an AJAX request

Having a small issue with ajax when working on my project. I have two actions in the view: <body> @Html.Action("SetSearchFilter") @Html.Action("FillTable") </body> The first action is a DropDownList: @Html.LabelFor(m => m.Manager, ...

Leveraging AngularJS for a Windows store app

After attempting to integrate AngularJS into my Windows store application, I came across a few recommended solutions: Unfortunately, these solutions did not work as expected. While I didn't encounter the Unable to add dynamic content error, AngularJS ...

Using Vue: Accessing a Vue component's method from within a named slot that has

Is there a more efficient way to access the functions of a Vue Component that is rendered within a named slot of my component? The current setup includes: ParentComponent.vue ... <util-component> <template v-slot:0> <child-co ...

Load images in advance using jQuery to ensure they are cached and retrieve their original sizes before other activities can proceed

When a user clicks on a thumbnail, I aim to display the full-size image in a div. To achieve this, I want to determine the original size of the image based on its source URL before it loads, allowing me to set the appropriate dimensions for the container. ...

Angularjs still facing the routing issue with the hashtag symbol '#' in the URL

I have recently made changes to my index.html file and updated $locationProvider in my app.js. After clicking on the button, I noticed that it correctly routes me to localhost:20498/register. However, when manually entering this URL, I still encounter a 4 ...

Trigger fixed element to appear/disappear when scrolling using JavaScript

I've tried multiple solutions, but I can't seem to get this functionality to work properly on my website. I'm attempting to create a "schedule a demo" button similar to the one on www.bamboohr.com Currently, I have the following html, css, ...

Discovering the keycode for the GO button in JavascriptDiscovering the keycode

Can anyone help me figure out how to find the keycode for the GO button using Javascript in an Android browser? ...