Reset filter when the "All" option is chosen in Vue.js

There is an array of objects that looks like this:

obj=
[{name: 'joe', job: 'teacher', city: 'miami'},
{name: 'bill', job: 'police', city: 'yorkshire'},
{name: 'sarah', job: 'driver', city: 'michigan'}]

A dropdown menu contains these options:

<select v-model="selected">
  <option>blue</option>
  <option>green</option>
  <option>black</option>
  <option>all</option>
</select>

When an option is selected, it corresponds to an object in the array:

if (selected === "blue") {
  optionSelected = 'joe'
} else if (selected === "green") {
  optionSelected = 'bill'
} else if (selected === "black") {
  optionSelected = 'sarah'
} else if (selected === "all") {
  // unsure what to do here?
}

The filtering process is done as follows:

obj = obj.filter(object => object.name === optionSelected)

If I select blue, then my obj will be

{name: 'bill', job: 'police', city: 'yorkshire'}
. However, I am uncertain about how to filter for all. When all is chosen, the obj should revert back to containing all values, such as:

obj=
[{name: 'joe', job: 'teacher', city: 'miami'},
{name: 'bill', job: 'police', city: 'yorkshire'},
{name: 'sarah', job: 'driver', city: 'michigan'}]

Is there a way to achieve this?

NOTE: The code architecture cannot be altered.

Answer №1

To simplify the process, consider using an object that associates colors with names instead of lengthy if..else if statements.

const colorNameMap = {
  blue: 'joe',
  green: 'bill',
  black: 'sarah',
  all: false // can be omitted since undefined is considered falsy
}

Next, compare the selected color to the values in the map. If there's no match, return the entire obj as it is.

const name = colorNameMap[this.selected]
const filtered = name ? obj.filter(o => o.name === name) : obj

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

Mastering the art of integrating a multi-step form in React

While developing a multi-step form in my React 17.0.1 application using Typescript version 4.1.2, I came across this helpful guide: https://dev.to/sametweb/how-to-create-multi-step-forms-in-react-3km4 The guide was clear up to step 6, which I decided to s ...

Refreshing Ads JavaScript and Ad Placements with NextJS Navigation

My NextJS website utilizes a custom JavaScript provided by an ad provider for running ads. The script is typically structured like this: <script type="text/javascript" src="//cdn.adsite.com/static/js/ad.js" ></script> In ad ...

How can you effectively update the content of a Parent component in react-native by communicating with its child component?

In one of my child components, I have included a button for interaction. Now, within my Parent component, I have three of these child components arranged side by side. Whenever any of these child components are clicked/touched, I want to trigger changes ...

Retrieving chosen items from NextUI-Table

I am completely new to JavaScript and NextUI. My usual work involves C# and DotNET. I have a requirement to create a table with selectable items, and when a button is clicked, all the selected items should be passed to a function on the server that accepts ...

JavaScript Challenge: Calculate the Number of Visible Characters in a Div

I have a div with text content (a string of length S) that is fixed in size but can be of any length. When the text exceeds a certain point (referred to as L), it gets truncated, and the portion beyond that limit becomes invisible. In other words, characte ...

Stopping a function that is currently running on a website using Javascript

I have a script on my website that triggers a rain feature when a user clicks on a button. However, I am struggling to figure out how to allow the user to deactivate this feature. I've tried various methods such as using break, return, and timeouts, b ...

Creating a completely static website using Nuxt.js without any need for API requests: a foolproof guide

Currently experimenting with Nuxt.js to create a static website. Is it feasible to achieve a completely static site by eliminating the use of API calls for data retrieval? During my testing, I have successfully generated all necessary files and hosted th ...

Managing cookies in PHP and JavaScript can present challenges due to variations in how different browsers

Our website utilizes ExpressionEngine as the CMS and Magento's cart for e-commerce. I am encountering challenges with cookies and their accessibility in various sections. A cookie is used for storing search selections, allowing users to return to our ...

Excessive duration of execution (suspected loop leakage), C

My friend and I have been tackling a school task that involves sorting one array based on the order of another array. Our solution works perfectly, but the auto correction system rejects it due to exceeding the time limit. Despite optimizing by minimizing ...

Using React JS to iterate over an array and generate a new div for every 3 items

It's a bit challenging for me to articulate my goal effectively. I have a JSON payload that looks like this: { "user": { "id": 4, "username": "3nematix2", "profile_pic": &qu ...

The form yields no response and fails to send any data

Ensuring that the form on this site successfully sends the name and phone number is crucial. However, upon clicking the send button, I encounter an empty modal window instead of a response indicating whether the data was sent or not. The contents of the fi ...

Tips for deploying a Nuxt application using an alternative command line interface

Despite my best efforts scouring the internet for a solution, I have yet to find a method to resolve my issue. The problem lies with my nuxt.js SPA being blocked by my company firewall when accessed by other users at the designated host/port. While servin ...

Compatibility of HTML5 websites with Internet Explorer

Following a tutorial on HTML5/CSS3, I meticulously followed each step to create a basic website. While the demo of the site worked perfectly in Internet Explorer 8 during the tutorial, my own version did not display correctly when viewed in IE8. I discove ...

Guide to configuring the initial lookAt/target for a Control

I'm looking to establish the initial 'lookAt' point for my scene, which will serve as both the center of the screen and the rotation control's focus. Ideally, I'd like to set a specific point or object position rather than rotation ...

Using jQuery, we can replace all `<span>` elements with `<img>` elements and then verify if the images have been successfully loaded

Similar Inquiry: jQuery check if image is loaded I find myself in a scenario where the following HTML structure is utilized: <div class="image"> <img class="" src="content-images/1.jpg"> <span class="slide" rel="content-images/ ...

Enhancing Label and Input Elements with Dynamic CSS through jQuery Values

Edit : I am aware that their is a question mark in the jQuery, CSS and HTML. Due to it being generated automatically by Framework I cannot remove it. I'm trying to apply dynamic styling to the input and label elements in my HTML using jQuery. However ...

Limiting the length of numbers in Material UI

Is there a way to restrict user input to only numbers with a maximum length of 3 in Material UI? <TextField id="score" label="score" className={classes.textField} name="totalScore" margin="normal" defaultValue={score} /> We specifically ...

Guide on creating a cookie in express following a successful API call

Throughout my entire application, I utilize the /api route to conceal the actual API URL and proxy it in express using the following code: // Proxy api calls app.use('/api', function (req, res) { let url = config.API_HOST + req.url // This ret ...

The scope of this variable in Node.js results in an undefined response

Have you ever noticed the difference in behavior when executing JavaScript code in Google Chrome's console compared to running the same logic in a file using Node.js? function foo() { console.log( this.bar ); } var bar = "global"; foo(); In Chr ...

The value of the comment box with the ID $(CommentBoxId) is not being captured

When a user enters data in the comment box and clicks the corresponding submit button, I am successfully passing id, CompanyId, WorkId, and CommentBoxId to the code behind to update the record. However, I am encountering an issue as I also want to pass the ...