Filter array with multiple conditions and that some of them can be null

filtering an array of json objects by multiple properties
javascript filter array multiple conditions
javascript array.filter multiple arguments
javascript filter array of objects by multiple properties
javascript filter array multiple values
typescript filter array multiple values
javascript filter array of objects with multiple conditions
array filter multiple conditions php

I have a JS file that is used to render a vuetify v-list, which can have 2 levels (nodes with children and these are optional).

I need to add a filter from a search box that the user enters, I could filter the first level, but I have problems with the second because sometimes they have the property "children" in null and other times they have values. The menu is this:

const Menu = [
    {
        heading: null,
        icon: "mdi-security",
        text: "Login",
        url: {
            name: "login"
        },
        exactUrl: false,
        children: null,
        meta: {
            publicPath: true
        }
    },
    {
        heading: null,
        icon: "search",
        text: "Lista de Funcionarios",
        url: {
            name: "home"
        },
        exactUrl: true,
        children: null,
        meta: {
            publicPath: true
        }
    },
    {
        heading: {
            text: "Mantenimientos",
            publicPath: false
        },
        icon: null,
        text: "",
        url: null,
        exactUrl: null,
        children: null,
        meta: null
    },
    {
        heading: null,
        icon: "mdi-account-group",
        text: "Departamentos",
        url: {
            name: "departamentos"
        },
        exactUrl: false,
        children: null,
        meta: {
            publicPath: false
        }
    },
    {
        heading: null,
        icon: "mdi-account-circle",
        text: "Funcionarios",
        url: {
            name: "funcionarios"
        },
        exactUrl: false,
        children: null,
        meta: {
            publicPath: false
        }
    },
    {
        heading: null,
        icon: "settings",
        text: "Operación",
        url: null,
        exactUrl: false,
        children: [{
            icon: "add",
            text: "Cargar Pedidos",
            url: {
                name: "departamentos"
            }
        },
        {
            icon: "playlist_add_check",
            text: "Aprobar Pedidos",
            url: {
                name: "areas"
            }

        },
        {
            icon: "content_copy",
            text: "Remitir Pedidos",
            url: {
                name: "maps"
            }
        }
        ],
        meta: null
    },
];

export default Menu;

And my computed function is this:

filteredMenu() {
  return this.menus.filter(menu =>
    menu.text.toLowerCase().includes(this.search.toLowerCase())
  );
}

How could I filter at the same time on both levels?

EDIT 1:"

Expected Result:

Filters an array of objects with multiple match-criteria. � GitHub, to render a vuetify v-list, which can have 2 levels (nodes with children and these are optional). I need to add a filter from a search box that the� The filter() method creates a new array with all the elements that pass the test implemented by the callback() function. Internally, the filter() method iterates over each element of the array and pass each element to the callback function. If the callback function returns true, it includes the element in the return array.

you can use a helpful function _isExist()

const _isExist = (menu, value) => menu.text.toLowerCase().includes(value.toLowerCase())

and you can use it for searching inside the children array if exist

filteredMenu() {
  return this.menus.filter(
    menu =>
        _isExist(menu, this.search) ||
        (menu.children && menu.children.some(childMenu => _isExist(childMenu, this.search))),
  )
}

How to use an advanced filter with an OR condition in Google Sheets, Filters an array of objects (one level-depth) with multiple criteria. return filterKeys.some(key => { // ignores an empty filter if (!filters[key].length) return true; I want to filter them to find students in the class so can you give a sample of code ? Another suggestion caught my attention was to allow filter by range, e.g. details.capacities.fuel > 30 && details.capacities.fuel < 50. Supporting array and also object as the filter criteria not only increase the base-code but also the current approach does not allow filter by ranges, so I decided to simplify the code and delegate the search criteria to the object that describe the filters

you can use Destructuring assignment in order to get a value and set a predefined value, then using Some you can check for a truthy condition on an Array.

so in other words, what you need to do is the following:

filteredMenu() {
  return this.menus.filter(menu => {
    // check if the parent has the value
    const parentIncludesText = menu.text.toLowerCase().includes(this.search.toLowerCase())

    // define a predefined value in case 'children' is null
    const { children = [] } = menu || {}

    // check if some of the childs has the value.
    const childrenIncludesText = children.some(child => child.text.toLowerCase().includes(this.search.toLowerCase()))

    // then return the result of the parent and the children.
    return parentIncludesText || childrenIncludesText
  });
}

array_filter - Manual, Knowing the trick will save you hours, so you can filter multiple conditions easily. In this post, I want to share a few more advanced filter options, such as� For the next step, add a Data Operations - Filter array action - renamed to Filter Tasks By Status. In the From field, select the value from the Get Rows step. For the condition, click on Edit in advance mode and enter the expression below.

Create a function that you can call recursively.

methods: {
  filterMenuItems(menuItems) {
    return menuItems.filter(menuItem => {
      let found = menuItem.text.toLowerCase().includes(this.search.toLowerCase());
      if (!found && Array.isArray(menuItem.children)) {
        found = this.filterMenuItems(menuItem.children);
      }
      return found;
    });
  }
}

Now your computed property can return this.filterMenuItems(this.menus)

filteredMenu() {
    return this.filterMenuItems(this.menus);
}

This allows for infinite sublevels as well

FILTER function - Office Support, Here's a function that will filter a multi-demensional array. This filter will return only those items that match the $value given <?php /* * filtering an array */ function� If you’re starting in JavaScript, maybe you haven’t heard of .map(), .reduce(), and .filter().For me, it took a while as I had to support Internet Explorer 8 until a couple years ago.

If im correct you want to check if its children is not null too? You can use &&

filteredMenu() {
  return this.menus.filter(menu =>
    menu.children && menu.text.toLowerCase().includes(this.search.toLowerCase())
  );
}

Find Array Elements That Meet a Condition, Syntax � An array can be thought of as a row of values, a column of values, or a combination of rows and columns of values. � The FILTER function will return an� I can do get a item from the array by filter the array. My solution: get a link from tweet text. 1. Trigger: Button . 2. Action: Compose. Name: StringArray

An Introduction to MongoDB Query for Beginners, how to filter the elements of an array by applying conditions to the array. You can perform these tasks using a combination of the relational and logical operators. the array, and you can apply multiple conditions by connecting them with the Some problems require information about the locations of the array elements� I'm going to start with a basic technical description of what arrays are and how they are used by most programming languages before I shift into the other ways PowerShell makes use of them. An array is a data structure that serves as a collection of multiple items. You can iterate over the array or access individual items using an index.

How to use the Excel FILTER function, Filter on 'Array of Documents' Columns If you want to query only the data with NA (or null) in some columns, you can use 'null' as the condition like below. The input array of your “Filter array” action is not an empty array, it has one element which is an empty string, so the result that your @empty() function returned is false. Please check if there is something wrong with the formula of your “Get Attendees” action. Besides, also please check if the appointment has invited other Attendees.

Excel FILTER function - dynamic filtering with formulas, The Excel FILTER function filters a range of data based on supplied criteria, and To return nothing when no matching data is found, supply an empty string ("") for if_empty: If the include array includes any errors, FILTER will return an error. To compare two lists and extract common values, you can use a formula based � var newArray = array.filter(function(item) { return condition; }); The item argument is a reference to the current element in the array as filter() checks it against the condition. This is useful for accessing properties, in the case of objects. If the current item passes the condition, it gets sent to the new array. Filtering an array of objects

Comments
  • Can you provide a simple demo?
  • yes, I have added an image of the expected result
  • Where's the destructuring?
  • @JaredFarrish const { children = [] } = menu|| {}
  • That's a way of doing it. The way you had it before (const children = menu.children || []) worked fine as well. I'd give you an upvote without it (I think it confuses the issue), but won't downvote it either.
  • yes @JaredFarrish as soon as you told me, I noticed :) thank you for noticing that before :D
  • I really liked your recursive proposal, although it didn't work at all. I have added some console.log to check the filters. With the filter "ar" excludes "Login" of the first level, but does not exclude "Remitir Pedidos" of the second level, although in the console it is seen that the match is printed "false". I leave a capture of the result: i.imgur.com/i2blR9k.png
  • This is expected. 1 of the child items contains "ar" (Cargar Pedidos). We don't filter out child items.
  • No, the filter condition has to be: 1. The text property of the first level must be filtered even if children are null or have value. 2. If children is not null, this must also be filtered by the text property