Sort through an array of objects based on the values they contain

I am working with an array of objects

var array = [
 {id: true, category: "cat1", name: "test1"},
 {id: true, category: "cat2", name: "test2"},
 {id: true, category: "cat3", name: "test3"},
 {id: true, category: "cat4", name: "test4"},
 {id: true, category: "cat5", name: "test5"}
]

I am trying to filter this array based on matching values. Here is the script I am using:

let filtered = this.array.filter((array) => {
    return array.name.toLowerCase().includes(this.keyword.toLowerCase());
});

var category = [];

if(category.includes("All")) {
   return filtered;
} else {
   return filtered.filter((array) => {
     var keys = Object.keys(array);
     var matchFilter = false;
     category.forEach((key) => {
       if(array[key] === true) {
         matchFilter = true;
       }
     });
     return matchFilter;
   });
}

Additionally, I have implemented checkboxes on the frontend to store values for the variable category

<input type="checkbox" v-model="selectedCategory" value="All">
<input type="checkbox" v-model="selectedCategory" value="1">
<input type="checkbox" v-model="selectedCategory" value="2">
<input type="checkbox" v-model="selectedCategory" value="3">
<input type="checkbox" v-model="selectedCategory" value="4">
<input type="checkbox" v-model="selectedCategory" value="5">

Currently, the filtering only considers the ID values. However, I aim to expand the filtering to include category and name values as well.

Answer №1

It seems that you can achieve this specific task using Array.protoype.filter.

var array = [
 {id: true, category: "cat1", name: "test1"},
 {id: true, category: "cat2", name: "test2"},
 {id: true, category: "cat3", name: "test3"},
 {id: true, category: "cat4", name: "test4"},
 {id: true, category: "cat5", name: "test5"},
]

const getByCateg = (arr, categ) => {
  if (categ === "All") return array;
  return arr.filter((item) => item.category === categ);
}

console.log(getByCateg(array, "All"), getByCateg(array, "cat2"))

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

Pagination activates on the second tap

Check out my example on jsFiddle: https://jsfiddle.net/0se06am5/ class Pagination extends React.Component { constructor(props) { super(props); this.state = { current: 1 }; this.items = ['a', 'b', 'c&ap ...

Unable to successfully remove item by ID from mongoDB within a Next.js application

Currently, I am developing an application using NextJS for practice purposes. I'm facing challenges in deleting single data from the database with the findByIdAndDelete function. Error encountered: CastError: Cast to ObjectId failed for value "undef ...

Enhance and modify data with AngularJS, while also incorporating new information into the

Working on a feature where Worklists can be added and edited or deleted from local storage. Encountering an issue where after editing a worklist, it cannot be added anymore as it updates the existing worklist data that was selected for editing. (the edite ...

What could be causing my ul list to not be populated by ajax?

To populate the ul list with data from PHP code on page load, you can use the following ajax function. I appreciate any help in advance, and please forgive me if my explanation is not precise as I'm new here. This post contains mostly code snippets. ...

Laravel - Jetstream with InertiaJS: Implementing guards in the main header menu of AppLayout.vue

Is there a way to utilize guards for adding a specific admin menu entry using guards? I am aware that passing guard-"data" from controllers to view is possible as mentioned in the documentation: class UsersController extends Controller { public functio ...

Why is my Node.js Connect middleware Limit feature not functioning as expected?

Having an issue with server: var connect = require('connect'); var http = require('http'); var app = connect() .use(connect.limit('32kb')) .use(connect.urlencoded()) .use(connect.json()) .use(function(req, res){ console. ...

When attempting to import and utilize global state in a component, the error message "Cannot iterate over null object"

I am in the process of setting up a global state to keep track of various properties that I need to pass down to multiple components. const initialState = { username: '', selectedCategory: null, categoriesList: [], createdTaskTopi ...

Display options in Material-UI autocomplete only upon clicking the icon

Is there a way to display the options list only when clicking on the arrow icon as opposed to the textfield itself? I have reviewed the documentations without success in finding a solution. Example ...

Identifying Labels in ThreeJS

I have a simple Threejs code where I am experimenting with click events using Raycaster. By using the BOX geometry, I have created three cubes in my scene. Additionally, I have utilized CSS2DRenderer.js to add a label above one of the cubes. My goal is t ...

What is the best method for animating a display table to none or reducing its height to

My goal is to animate a header whenever the class collapseTest is applied. After some trial and error, I have come up with the following solution: http://jsfiddle.net/robertrozas/atuyLtL0/1/. A big shoutout to @Hackerman for helping me get it to work. The ...

Angular 6 canvas resizing causing inaccurate data to be retrieved by click listener

The canvas on my webpage contains clickable elements that were added using a for loop. I implemented a resizing event that redraws the canvas after the user window has been resized. Everything works perfectly fine when the window is loaded for the first ti ...

discord.js: Imported array not displaying expected values

I've been facing an issue with accessing elements from an imported array. Even though the array is successfully imported, attempting to access its elements using [0] results in undefined. Here's how I exported the array in standList.js: exports. ...

Learn how to continuously update the current timestamp in PHP using jQuery or JavaScript every second

I am currently developing a PHP cart timer script that utilizes PHP along with jQuery and JavaScript. By using the set-interval function, I am able to continuously retrieve the current time-stamp in PHP. Once the first product is added to the cart, the t ...

How can jQuery be employed to locate the position of an element within its group of siblings with a particular CSS class?

Here is an example of HTML code: <div class="component"> <div class="component"> <div class="component"> </div> </div> <div class="component"> <div class="somethingelse"> ...

What is the best way to reveal a hidden div using JavaScript after a form submission?

jQuery is not a language I am very familiar with, but I am attempting to display a simple animated gif when a form is submitted. When users click 'submit' to upload an image, I want the gif to show to indicate that the image is being uploaded. Th ...

Trouble with using .className for form validation

The .className is not applying the formValidation class on getWeight.length < 1 and getHeight.length < 1. I am stuck trying to figure out why this is happening after reviewing the code extensively. Any thoughts on what could be causing this issue? Y ...

Error: The object "request" has not been defined. This issue occurs when trying to execute an Action

$dd = "<a href='javascript:void(0);' id='requestsend$send_id' onClick='request($send_id,request_send);' class='post-add-icon inline-items'><button type='button' style='background: #ccc;' ...

Creating a clickable button that directs users to a webpage I designed as well

As part of my learning process, I am in the midst of creating my own website. My goal is to enhance user experience by enabling them to click on a button and seamlessly transition from one page to another. In my quest for knowledge, I have scoured the int ...

Using innerHTML in React to remove child nodes Tutorial

I'm encountering slow performance when unmounting over 30,000 components on a page using conditional rendering triggered by a button click. This process takes around 10+ seconds and causes the page to hang. Interestingly, setting the parent container& ...

Adding up table rows created using AngularJS with the help of jQuery

It might seem a bit strange, but I have a scenario where I need to use jQuery to sum all rows in a table. In this particular table, I'm utilizing angularjs to display a list of users, but I want to calculate the total sum of all rows using jQuery. Th ...