Screen the array and find at least one matching criterion

So, I've encountered a challenge that I'd like to address: Filtering an array based on specific conditions using Vue.js and lodash (or raw JavaScript).

The Objects I'm Working With

  • I have a list of Items. Each item may have (optional) categories.
  • The object Car can be assigned a category.

Array of Objects Items

"data": [
    {
      "id": 1,
      "title": "Item 1",
      "categories": [
        {
          "id": 4,
          "title": "category 4",
          "description": ""
        },
        {
          "id": 5,
          "title": "category 5",
          "description": ""
        }
      ]
    },
    {
      "id": 2,
      "title": "Item 2",
      "categories": []
    },
    {
      "id": 3,
      "title": "Item 3",
      "categories": []
    }
  ]

Object Car

{
  "category": {
    "id": 5,
    "title": "category 5",
    "description": ""
  },
  "title": "Test"
}

Objective

I aim to display only those Items that meet at least one of the following criteria:

  • The Item has at least one category that matches the category of the Car
  • The Item has no assigned category

My Approach

I'm currently using a computed property to filter this.items:

computed: {
        filteredItems: function () {
            let vm = this;
            return _.filter(this.items, function (item) {
                return _.includes(item.categories, vm.car.category);
            });
        }
    }

Current Outcome:

The filteredItems array is always empty.

Answer №1

It's important to conduct an additional level of validation on the categories because each item inside it needs to be tested against. Using regular JavaScript, you can achieve this with the some() method, which will return true if any of the items match.

let data = [{"id": 1,"title": "Item 1","categories": [{"id": 4,"title": "category 4","description": "",},{"id": 5,"title": "category 5","description": "",}]},{"id": 2,"title": "Item 2","categories": []},{"id": 3,"title": "Item 3","categories": []}]
let  car = {"category": {"id": 5,"title": "category 5","description": ""},"title": "Test"}

let filtered = data.filter(item => !item.categories || item.categories.length === 0 ||  item.categories.some(cat=> cat.id === car.category.id))
console.log(filtered)

Answer №2

To implement this functionality using the lodash library, you can utilize the following code snippet:

result = _.filter(data, ({categories}) =>
    _.isEmpty(categories) ||
    _.some(categories, cat => cat.id === car.category.id))

If you prefer to compare the entire category objects instead of just their ids, you can modify the code as follows:

_.filter(data, ({categories}) => 
    _.isEmpty(categories) || 
    _.some(categories, cat => _.isEqual(cat, car.category)
    ))

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

JavaScript: Break apart and tally the number of words within a given string

If I have an input string with the value "testing the string", I want to create a function that splits each word and counts how many times each word appears in the input string. The desired output should look like this: testing: 1, the: 1, string: 1 Than ...

Troubleshooting issue with Ajax.Actionlink not canceling request using jQuery's onBegin

In the "onBegin" ajax option of an ajax.actionlink, I have a function that is called. function cancelAction() { $.ajax({ data: { p: "test", z: "value" }, url: '@Url.Action("DoSomething", "TestCtlr")', type: "GET", ...

Control the HTML button's state according to the information received from the server

I am currently working with datatable Jquery and using an ajax call to retrieve data from the server. Let's assume that the database consists of three attributes: "Attribute1, Attribute2, Status". Depending on the Status attribute, I need to enable or ...

Receiving a blank array upon calling res.json() in Node.js script

I'm facing an issue with my code snippet that displays all posts, including the username and display picture of each user. Everything seems to be working fine as the log output is perfect. However, I'm struggling to return this data as a JSON obj ...

Display a 404 page on Vue router when the ID does not match

When it comes to displaying a 404 page if a parameter doesn't match, I'm a bit puzzled. For instance, if the user name is “joe” and someone tries to access “/joe/categories”, then the categories component should be displayed. Now, I want ...

Error in Vue.js and Socket.io - the server response cannot contain the wildcard '*' when the request has its credentials mode set to 'include'

I'm currently working on creating a chat app using Vue and Socket IO. Here's the error I'm encountering. This is my Node server code. And this is my Vue app code. My Node server and Vue app are separate entities. How can I resolve this i ...

Utilizing Provide/Inject in Vue 3 Typescript to retrieve a method within a component, encountering the possibility of an 'undefined' Error Object

Having trouble calling the loginWithRedirect function within the header.vue component using inject feature in Vue 3 and Typescript. ERROR in src/components/global/HeaderMenu.vue:77:17 TS2339: Property 'loginWithRedirect' does not exist on type ...

Leveraging Nuxt.js with Axios on Google Firebase hosting

When I deploy my project to Firebase hosting, I encounter an issue with the axios baseURL and/or proxy settings defaulting to local values instead of the ones specified in the nuxt.config.js. This results in 404 errors. Although hardcoding my URLs resolve ...

Website automation can be simplified by utilizing the Webdriver.io pageObject pattern, which allows for element selectors

Currently, I am following a specific example to define elements within pageObjects using the ID selector... var Page = require('./page') var MyPage= Object.create(Page, { /** * defining elements */ firstName: { get: function ( ...

Is there a way to implement a directive wrapper for ng-grid that allows the grid options to be specified using a directive attribute?

My goal is to create a reusable directive wrapper for ng-grid, where I can dynamically apply the ng-grid options through the use of an attribute. Below is the basic structure of the code that almost achieves what I am looking for: angular.module('my ...

Error encountered when assigning a value to a session array in PHP 7.0

I am the author of this script <?php session_start(); if($_POST["num"] > $_SESSION["ratings"][$_POST["title"]]) $SESSION["ratings"][$_POST["title"]] = $_POST["num"]; ?> Although my syntax seems correct to me, the IDE is showin ...

What is the reason behind not requiring to invoke the next function in a Sails.js controller method, even when it includes an asynchronous database query?

Sample controller function: fetchArticles: function(req, res) { Articles.find({}).exec(function(err, articles) { res.json(articles) // It appears this part is asynchronous // Is next() required here? }) } In my experience, I typicall ...

How can I add content to the body of a modal in Bootstrap 3?

My application has a button that, when clicked, is supposed to trigger a modal popup containing some data. I want the data in the modal to come from another application via a PHP file accessed through a URL. How can this be achieved? <?php echo '& ...

Utilizing a jQuery AJAX request to invoke a web method within a

My goal is to integrate jQuery mobile into an existing ASP.NET webform application. I am currently considering using pure HTML controls to create the jQuery Mobile page. I am aware that when making an AJAX call, I can access code-behind static web methods, ...

Question: How can I use the jQuery datepicker to ensure that the selected date remains in the

I recently created a webpage using a combination of HTML, PHP, and jQuery. The PHP script is designed to load all data where the date matches the one selected in the text input field generated by the jQuery datepicker. However, I encountered a problem whe ...

Optimal strategy for multiple <forms> needing the same <script> element

I find myself in a bit of a conundrum when it comes to figuring out the Vue way to handle this particular scenario. At the moment, I have two search inputs that utilize very distinct templates - one located in the navbar and the other at the page level. I ...

How can a button be linked directly to a particular list item?

I currently have a HTML tag within my React application that looks something like this: <ul> <li> Item 1 <button> Delete </button> </li> <li> Item 2 <button> ...

typical / easy-to-read way to declare arrays and utilize them

Which way do you think is more standard, readable, and efficient for array declaration? Option 1: $days = array(1=>'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'); Access values u ...

Issue with autoplay slideshow functionality not activating when opened in a new tab

The owl.carousel.js plugin is used for creating a jQuery slideshow. Initially, the slideshow works correctly, but I noticed that the autoplay feature stops working when I open a new tab in Firefox or Chrome. Demo : Demo : $(document).ready(function () ...

Modifying the Vue page background directly from a page: a step-by-step guide

UPDATE: I recently discovered that I need to modify the body background-color, but I am unsure of how to accomplish this from within the style of this page based on the wrapper's class. The class is determined by the data values. I aim to change the ...