Searching for items in an array of objects using Vue.js

Here is an example of a Laravel API response:

{
id:1, 
name: "Text",
category: {
            id: 1,
            name: "Text 2",
          },
tags:[
       {
         id: 1,
         name: "Tag1",
       },
       {
         id: 2,
         name: "Tag2",
       },
     ],
},

In my front-end (using Vue.js), I have created a computed function to filter posts based on the user's selection of checkboxes associated with categories.

checkedCategory: []
.
.
let posts = this.posts;
if (typeof this.checkedCategory !== 'undefined' && this.checkedCategory.length > 0) {
          posts = posts.filter((post) => {
                     return this.checkedCategory.indexOf(post.category.name) > -1;})}

So far, everything is working fine and posts are successfully filtered by selected categories.

However, each post can have multiple tags as well. Since tags are stored in an array of objects, I attempted to modify the code using .includes instead of .filter, but it resulted in empty output.

checkedTags: []
.
.
let posts = this.posts;
if (typeof this.checkedTags !== 'undefined' && this.checkedTags.length > 0) {
          posts = posts.includes((post) => {
                     return this.checkedTag.indexOf(post['tags']) > -1;})}

Answer №1

Here is a solution that should do the trick:

let blogPosts = this.posts;
if (typeof this.checkedTags !== 'undefined' && this.checkedTags.length > 0) {
  blogPosts = blogPosts.filter(post => {
    return post.tags.some(tag => checkedTags.includes(tag.name))
  })
}

This code snippet filters the posts based on whether at least one tag matches with those in the checkedTags array. You can further modify it to check if all tags of the post are included using post.tags.every() depending on your specific requirements.

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

Node.js Promise delivering less than expected results

I've encountered an issue with a Promise that previously awaited a complete JSON string but now only returns a portion of it. I'm utilizing the Shopify API for customer creation, and this is the expected response structure: { "customer": { ...

Enhancing realism with ambient occlusion in three.js

After successfully converting my first cloth simulation from OpenGL to WebGL using three.js, I noticed that it looks a bit dull. I am hoping to add ambient occlusion for nicely shaded effects when the cloth collides with a ball. Unfortunately, my knowledge ...

The custom radio component available in the newest version of Vue is currently experiencing issues and is not working properly when

UPDATE: The active class rendering issue has been identified. Click logs data as expected. Expected https://i.sstatic.net/MYzH9.png Current https://i.sstatic.net/tPBVZ.png RadioInput <RadioInput v-model="form.userType" label="User Type" :opt ...

Tips for disabling scrolling on touch screens for input elements

I am facing an issue with a modal that is positioned on top of a scrollable document body. I am trying to prevent the scrolling of the document when I swipe my finger on the modal. $(document).on('touchstart touchmove', function(e){ e.preventDef ...

Assign the Firebase token to the JavaScript cookie value

Can a cookie store a token value? In my setup with js-cookie, Firebase auth/firestore, and Next.js, I am setting my cookie within the handleUser function like this: const handleUser = async (rawUser) => { if (rawUser) { const user = await fo ...

"Encountered an issue with loading a resource in the inspector within Angular

Using angular's ng-repeat, I am uploading some placeholder content. var app = angular.module("homeApp", []); app.controller("entriesView", function ($scope){ $scope.itemEntry = [ { image: "img/112013-priscilla-600.jpg", title: "y ...

Vue - Utilizing mapState in Vuex to display the contents of the first object within an array

I am trying to display the names array from the first object in players using mapState with Vuex. Currently, the objects in players are listed based on their titles, but I want to filter them based only on the names in the first object for the current page ...

observing calls made with twilio using javascript

My goal is to track the status of a phone call happening between two people using their phone numbers. Let's say +558512344321 and +558543211234 are currently on a call. As soon as the call begins, I want the browser to display "Call in progress," and ...

Understanding the flattening process of arrays using JavaScript - Detailed explanation required

Currently, I am immersed in the captivating world of Eloquent JavaScript. However, I have hit a roadblock with one of the exercises that involves flattening a multi-dimensional array. Despite my best efforts, I have been unable to crack the code. After f ...

Why bother re-rendering components in React that haven't had any changes in their state?

Within my main component, I have both a state and a static component nested inside. An issue arises when the state changes and triggers a re-render of the main component, causing the static component to also re-render unnecessarily. import { useState } fro ...

The updated Bootstrap 4 carousel is only working halfway as expected when attempting to double it up, causing the scroll loop to stop functioning

Discovering a fantastic carousel modification was an exciting find, which can be accessed Here. However, when attempting to place two carousels on one page, issues arose with the scrolling functionality. While I managed to make them operate on the correct ...

How can a parameter be added to a query string only when there is a value present in a textbox using JavaScript?

Hello everyone, I am looking to add parameters to a URL only if the search text box value is different from the default. I have three search text boxes and I want to include them in the URL. Below is my code snippet: $("#search-btn").click(function (e) { ...

Manipulate SVG elements by dragging them along the boundary of the path

Looking to achieve a specific functionality where I can drag and drop an element along the edges of a drawn path, rather than inside the path itself. To clarify, the goal is to move the red marked element on the black line bordering the path, allowing move ...

What is causing the lack of rendering in a React component after modifying the state?

Let me show you the compressed version of my code for a quick look const PropertiesList: FC = (estatesObject) => { const [estates, setEstates] = useState(Object.values(estatesObject)) const filterEstatesUp = () => { // sorting an arr ...

What is the best way to retrieve data from multi-dimensional JSON structures?

Looking to extract specific values from my JSON file. console.log( objects.assignments.header.report_type ); I need to display HOMEWORK Javascript $.ajax({ url: "/BIM/rest/report/assignment", type: "POST", dataTyp ...

React-Image-Annotate encountered an issue: SyntaxError - The import statement cannot be used outside a module

Encountering an issue while trying to set up react-image-annotate. Here is the problem I am facing initially: https://i.stack.imgur.com/XgYPd.png This is how I have implemented it: import React from 'react' import ReactImageAnnotate from ' ...

Using Axios to Integrate an API - Displaying a Username and Password Pop-up

I have been given a project that involves API integration. I have successfully retrieved data from the API, but there is a pop-up appearing asking for a username and password. Although I have these credentials, I would like to log in without that pop-up ap ...

What is the procedure for manipulating a string within an array of objects with a string key-value pair using underscore.js?

I am seeking a solution utilizing underscores, but I am open to a vanilla JS alternative if it proves to be the most effective option. My goal is to utilize array 2 to modify strings in the objects of array1 that either start with or end with the strings ...

Creating a jQuery plugin that allows for multiple plugin calls with customizable settings

Here is a jQuery plugin that I created: (function($){ $.fn.myPlugin = function(options) { if (!this.length) { return this; } var settings = $.extend(true, {}, $.fn.myPlugin.defaults, options); $w=$(this); $w.bind("click ...

What is the best way to execute a series of AJAX functions one after the other in JavaScript?

Currently, I am working on a project that involves editing multiple elements within a window simultaneously using AJAX. My goal is to have all "open for editing" elements saved when the user clicks the save button for the entire window. However, I encount ...