Obtain specific element from a list using attribute in JavaScript

Imagine having a collection like this:

navigation: [
        {
          title: "Overview",
          icon: "mdi-view-dashboard",
          active: false,
          id: 0,
        },
        {
          title: "Personal Information",
          icon: "mdi-clipboard-account-outline",
          active: false,
          id: 1,
        },
        {
          title: "Addresses",
          icon: "mdi-map-marker",
          active: true,
          id: 2,
        },
        {
          title: "Recent Orders",
          icon: "mdi-clipboard-text-multiple",
          active: false,
          id: 3,
        },
        {
          title: "Favorites List",
          icon: "mdi-playlist-star",
          active: false,
          id: 4,
        },
      ],

Is there a way to retrieve the element with active: true without using multiple if statements?

Answer №1

Consider using the filter method:

const filteredList = items.filter(item => item.available)

You'll receive a list of elements that are marked as available; In case of no matches, it will return an empty array [].

Answer №2

Implement the filter method effortlessly using this example.

const navigation = [
  {
    title: "Overview",
    icon: "mdi-view-dashboard",
    active: false,
    id: 0,
  },
  {
    title: "Personal Information",
    icon: "mdi-clipboard-account-outline",
    active: false,
    id: 1,
  },
  {
    title: "Addresses",
    icon: "mdi-map-marker",
    active: true,
    id: 2,
  },
  {
    title: "Recent Orders",
    icon: "mdi-clipboard-text-multiple",
    active: false,
    id: 3,
  },
  {
    title: "Wishlist",
    icon: "mdi-playlist-star",
    active: false,
    id: 4,
  },
];

const active = navigation.filter((elem)=>elem.active);

console.log(active);
      

Answer №3

Learn more about Array.filter

Here is an example:

const numbers = [ -2, -4, -1, 5, -3, 8, -7];
const negativeNumbers = numbers.filter(number => number < 0);

console.log(negativeNumbers); // Outputs: -2, -4, -1, -3, -7

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

collection of assurances and the Promise.all() method

Currently, I am dealing with an array of Promises that looks like this: let promisesArray = [ service1.load('blabla'), service2.load(), // throws an error ]; My goal is to execute all these Promises and handle any errors that occur, as ...

Adjusting the background color of <tr> depending on the number of <tr> elements in the HTML using CSS

When working on my HTML page, I have utilized multiple <tr> tags with different bgcolor values such as: <tr bgcolor="#000000"> <tr bgcolor="#E5F1CC"> <tr bgcolor="#D30A0A"> <tr bgcolor="#656766"> I am aiming to assign unique ...

Preloading and rendering an image onto a canvas in a Vue single-page application is not functioning as expected

I am working on a Vue 3 SPA where I am manipulating canvas elements. To preload my image, I am using the function provided below: async preloadLogo () { return new Promise( (resolve) => { var logo_img_temp = new Image(); const logo_s ...

How can I use Express JS and Mongoose to update an array of objects in MongoDB?

Encountered a TypeError: result.taskList[id].push is not a function const taskcancel = (user, pswd, id) => { return db.Todotasks.findOne({ username: user, password: pswd }).then((result) => { if (result) { console.log(result.tas ...

Having trouble parsing JSON with Ajax in Pusher using PHP?

I am facing an issue while sending multiple parameters using the Pusher AJAX PHP library. This is the error I encounter: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data Here is my PHP and JS code: <script src="https: ...

Managing checkbox behavior using ajax

Currently, I am utilizing a CSS toggle button to display either active or inactive status. This toggle button is achieved by using an HTML checkbox and styling it with CSS to resemble a slide bar toggle. The assigned functionality involves binding the onCl ...

Sync State with Data from API Query

I have a scenario where I need to fetch data from two different APIs and update their states separately. Afterward, I am iterating through the NBA data and looping through the animeData object to update the allData state, which will be an array of object ...

Having trouble with gapi.client.request() not functioning properly?

I've been trying to use the Google API for freebase, and even though I'm following the correct call as per the documentation, it seems like there is an issue. The Chrome debugger is showing that something is wrong with this supposedly simple call ...

Node is throwing a 302 error on Localhost:3000

Looking for some guidance as a beginner trying to create and run a nodejs application. Encountering an error while running server.js via nodemon, the console displays the following: Express server listening on port 3000 Mongoose default connection open t ...

Limiting the number of times a specific character appears using a regular expression

Currently, I am in search of a regular expression that allows me to set a limit on the number of times a special character can appear. For instance, if I want to restrict the occurrence of * to a maximum of 5 times in the entire text, then the output shou ...

Error VM5601:2 encountered - Unexpected token "<" found in JSON at position 10

I am trying to retrieve data using Ajax and jQuery, but I keep encountering an error that I cannot figure out how to fix. VM5601:2 Uncaught SyntaxError: Unexpected token < in JSON at position 10 Below is the code I am working with. Model public f ...

Tips for enabling custom object properties in Chrome DevTools

In my typescript class, I am utilizing a Proxy to intercept and dispatch on get and set operations. The functionality is working smoothly and I have successfully enabled auto-completion in vscode for these properties. However, when I switch to the chrome d ...

What is the best way to retrieve the data from a specific section when a checkbox is selected in Angular 2?

When I select a checkbox for any section and then click the submit button, I want to display the details of that section in the console. Can someone assist me with this? **Stackblitz link:** : https://stackblitz.com/edit/angular-q7y8k1?file=src%2Fapp%2Fa ...

Angular Material: div not being filled by layout-fill

<!-- Container Div --> <div layout-fill> <!-- Image Div --> <div layout="column" layout-align="center center" class="coverImage" layout-fill> <md-content class="md-padding"> Sample Text Here ...

The error message "Equals is not defined: Selenium IDE Custom Format" indicates that the function "

I've been working on enhancing the functionality of the selenium IDE through custom functions. I successfully added my custom functions to user-extensions.js and they work as expected within the IDE. However, I encountered issues when trying to export ...

Dynamically add a plugin to jQuery during execution

After installing jQuery and a jQuery-Plugin via npm, I am facing the challenge of using it within an ES6 module. The issue arises from the fact that the plugin documentation only provides instructions for a global installation through the script tag, which ...

Retrieve specific information from a JSON file and save it in an array using Node.js/JavaScript

My goal is to extract all log details from a JSON object, but the issue is that the key for each user is constantly changing. let userJsonObject = { "user_1":{ "id":"user_1", "log":"de-data", ...

There was a parsing error due to an unexpected token, and we were expecting a comma instead

Below is the code snippet written in react js: class Posts extends Component { render() { return ( {console.log('test')} ); } } When I executed this code, an error occurred stating: Parsing error: Unexpected token, expected " ...

Preventing jQuery plugin from loading in Ajax response

When I receive an AJAX response from page 2, I want to load the jQuery rating plugin on page 1. Although I obtained data from a database, I am unable to load the rating plugin. Here is my script: temp1.php <script type="text/javascript" src="review-p ...

Exploring elements in Javascript

I am attempting to retrieve values from various elements when a 'a' element is clicked. Consider the following code: <tr data-id="20"> <div class="row"> <td> <div class="btn-group"> <a data-checked= ...