Refine your search with a JSON object description in expressJS and UnderscoreJS

[
  {
    "id": 1,
    "description": "Empty the garbage bin",
    "completed": false
  },
  {
    "id": 2,
    "description": "Dine out for dinner",
    "completed": false
  },
  {
    "id": 3,
    "description": "Exercise at the fitness center",
    "completed": true
  }
]

ABOVE IS AN EXAMPLE ARRAY.

I am looking to retrieve only objects that meet specific criteria.

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var _ = require('underscore');

app.get('/todos/query/:des', function (req, res){
    var descriptionToFilter = req.params.des;
    console.log(descriptionToFilter);

    var filteredDesArr = _.where(todos,function(todo){
        todo.description.includes(descriptionToFilter.toLowerCase());
    });

    res.send(filteredDesArr);


});

How is this accomplished? How can I pass a method as an argument within underscore.where?

Answer №1

When using Underscores where function, keep in mind that it takes a key:value object as input rather than a function. This is especially useful when you already know which properties you are looking for.

Here are some examples:

var completed = _.where(todos,{completed:true});

var gymCompleted = _.where(todos,{completed:true,description:"Hit the gym"})

The where function will return all elements that match the specified properties, while findWhere will only return the first matching element.

If your filtering requirements are more complex and involve specifying a predicate, then you will need to utilize the filter function, either through underscore or regular JavaScript.

Answer №2

If you're working in plain Javascript, you have the option to utilize Array#filter along with a specified callback function.

function filterByStatus(item) {
    return item.status === 'completed';
}

function filterById(id) {
    return function (item) {
        return item.id === id;
    };
}


var items = [{ id: 1, task: "Clean the garage", status: 'incomplete' }, { id: 2, task: "Go grocery shopping", status: 'completed' }, { id: 3, task: "Read a book", status: 'incomplete' }];

console.log(items.filter(filterByStatus));
console.log(items.filter(filterById(2)));

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

Double invocation of useEffect causing issues in a TypeScript app built with Next.js

My useEffect function is set up with brackets as shown below: useEffect(() => { console.log('hello') getTransactions() }, []) Surprisingly, when I run my app, it logs "hello" twice in the console. Any thoughts on why this might be ...

Converting a JavaScript function to CoffeeScript, accepting jQuery's .map function and Selectors as parameters

I'm in the process of converting some JavaScript code into CoffeeScript and encountering an issue with a particular function. Here is the original functioning JS: $(".comformt_QA").change(function(){ var array = $(".comformt_QA").map(function() { ...

Any tips for filtering an array within an array of objects using the filter method?

I have an array of products and models that I am currently filtering based on 'id' and 'category'. var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.products = [{ 'id': 1, ...

Having trouble displaying real-time camera RTSP streaming using Angular

I am currently in the process of developing a web application using Angular and I need to incorporate a window that displays live RTSP streaming. Upon conducting research, I discovered that this can be achieved by utilizing the JSMpeg JavaScript library. ...

Learn how to implement drag-and-drop functionality in React by making a component

I am currently experimenting with dragging a component using the react-dnd library. I wanted to replicate functionality similar to this example, specifically only focusing on dragging at the moment. In my application, I have imported and utilized the rea ...

Is there a way to ensure that the line numbers displayed for JavaScript errors in Chrome are accurate?

I suspect either my webpack configuration or my npm run dev script are causing the issue, but I'm unsure of what exactly is going wrong. While running my application in development mode, I encounter error messages like: Uncaught TypeError: this.props ...

Issue with using custom SQL queries in Winston with PostgreSQL and a specific table name

const logger = new (winston.Logger)({ transports : [ new winston.transports.PostgreSQL({ connString : 'xxxxxxxxxxx', schema : 'public', //tableName : 'logEntry', customSql:'INSERT INTO publ ...

Error: module 'next/react' not found

Recently delving into next.js, I encountered an error after creating a project with npx create-next-app. Oddly enough, the app still runs despite this issue. { "resource": "/E:/codes/news-website/news-website/pages/index.js", ...

Tips for efficiently loading data into a vuex module only when it is required and addressing issues with async/await functionality

Is there a method to load all the data for a Vuex store once and only load it when necessary? I believe there is, but I am having trouble implementing it. I'm not sure if it's due to my misunderstanding of Vuex or Async/Await in Javascript promi ...

Using a git repository as a dependency in your project and then importing the dependency

Struggling to integrate a git repository as a component has been my challenge for the past day. Despite trying multiple approaches, none of them seemed to work when I ran npm i. Here are some of the methods I attempted: npm install from Git in a specific ...

uncaughtException unable to capture thrown Errors

Currently, I am developing an api using Node.js and came across a feature that allows me to review errors before crashing my app (uncaughtException). Please refrain from discussing the drawbacks of this feature as I am already familiar with them. The iss ...

Encountering a 404 error when trying to navigate to the next route using the Link component

Having issues with my login route. I've added a Link to the login route inside a button tag in my Navbar component, but when I try to access the route, I'm getting a 404 error page. --app ----pages ------component --------Navbar.js ----- ...

The accumulation of keydown events in VueJs

Currently, I am developing a feature where a <textarea> field starts to fade out as soon as the user begins typing using v-on:keydown. However, if the user continues typing, the fading effect resets to keep the opacity: 1. Unexpectedly, the behavior ...

Restore the button to its original color when the dropdown menu is devoid of options

Is it possible to change the button colors back to their original state automatically when a user deselects all options from my dropdown menu? The user can either uncheck each option box individually or click on the "clear" button to clear all selections. ...

storing audio files locally with Vue.js

Looking for a way to store a sound locally for my Battleship game rather than referencing it on the internet. Here's the code that triggers the sound: @click.prevent="fireSound('http://soundbible.com/grab.php?id=1794&type=mp3')" I atte ...

How can I uncover the necessary cache key for a module in webpack?

Currently, I am utilizing the require method to load a sizable file that I need to clear from cache once it is no longer needed. Unfortunately, without this process, each file remains in memory indefinitely, which is not ideal. On a local level, executin ...

When trying to access the same path, useEffect does not trigger

I integrated the API to execute when the screen is loaded using useEffect in Next.js v10. The code implementation is straightforward: ... const fetchAPI = async () => { try { await axios.get({ .... }) } catch (e) { console.error(e) } } R ...

Is it possible for the user/website to access the express res.locals variables?

In the process of developing a Node app with Express and Passport, I have incorporated middleware in my main server.js file as shown below: // Function to protect urls function isProtected(req, res, next) { if (req.isAuthenticated()) { // User ...

Retrieving data from an HTML input tag and storing it in a variable

I'm currently working on a project that involves reading the contents of an uploaded file through an input tag and storing it in a variable. My goal is to then use an algorithm to decrypt the .txt file: <input type="button" value="decrypt" id="dec ...

Error message "electron-builder node-gyp encounters an issue with building for macOS-x86_64 while trying to link with a file that was built for macOS-arm64" finding a mismatch with architecture

Summary Can someone guide me on cross compiling an electron.js app, with a native-addon, for both Apple and Intel processors? Detailed Description I am facing issues while attempting to cross compile an electron.js app containing native-addons for both ...