Filter JSON object array based on multiple criteria using JavaScript

users = [
  {
    "username": "Alice",
    "firstName": "Alice-U",
    "lastName": "Wonderland"
  },
  {
    "username": "bob",
    "firstName": "Bob-u",
    "lastName": "Builder",
  },
  {
    "username": "charly",
    "firstName": "Charly-u",
    "lastName": "Brown",
  }
]

In this scenario, I am seeking a method to filter the user array based on multiple criteria. For instance:

Search Criteria: { "username" : "Alice" } would yield:

{
    "username": "Alice",
    "firstName": "Alice-U",
    "lastName": "Wonderland"
}

For example:

{ "username" : "charly", "firstName": "Charly-u" }
should return :

{
    "username": "charly",
    "firstName": "Charly-u",
    "lastName": "Brown",
}

The goal is to achieve precise string matching utilizing either JavaScript or jQuery.

Answer №1

Utilize the .every method to verify that all of the specified criteria keys align:

function filterBy(list, criteria) {
  return list.filter(candidate =>
    Object.keys(criteria).every(key =>
      candidate[key] == criteria[key]
    )
  );
}

let users = [
  { "username": "Alice", "firstName": "Alice-U", "lastName": "Wonderland" },
  { "username": "bob", "firstName": "Bob-u", "lastName": "Builder" },
  { "username": "charly", "firstName": "Charly-u", "lastName": "Brown" }
];

console.log(filterBy(users, { "username" : "Alice" }));
console.log(filterBy(users, { "username" : "charly", "firstName": "Charly-u" }));

Answer №2

Instead of using Array.prototype.filter(), why not try filtering only the element that has username="Alice"? You can actually add multiple object keys inside your filter's arrow function while filtering an array of objects. Here is an example:

user.username ==='Charly' && firstName==='Charly-u'

users = [{
    "username": "Alice",
    "firstName": "Alice-U",
    "lastName": "Wonderland"
  },
  {
    "username": "bob",
    "firstName": "Bob-u",
    "lastName": "Builder",
  },
  {
    "username": "charly",
    "firstName": "Charly-u",
    "lastName": "Brown",
  }
];

result = users.filter(user => user.username ==='Alice');

console.log(result);

Answer №3

Is it possible to simplify this using just a function with a for loop? //call this.filterIt( ‘username’ , ‘Alice’, users);

//function
Function filterIt (key, value, arr){
result = [];
for ( a in arr){
   if (a[key] == value) result.push(a);
}
return result;
}

Answer №4

If you need to perform an exact search, you can implement a search function like this:

function customSearch(term) {
  return data.filter(({username, firstName, lastName}) => {
    return username.toLowerCase() === term.toLowerCase() ||
          firstName.toLowerCase() === term.toLowerCase() ||
          lastName.toLowerCase() === term.toLowerCase()
  })
}

Rather than comparing each key individually, you can iterate through all object properties using Object.keys.

For a more flexible matching that finds the search term anywhere, you can use the following function:

function customSearch(term) {
  return data.filter(({username, firstName, lastName}) => {
    return username.toLowerCase().indexOf(term.toLowerCase()) > -1 ||
           firstName.toLowerCase().indexOf(term.toLowerCase()) > -1 ||
           lastName.toLowerCase().indexOf(term.toLowerCase()) > -1
   })
}

This method will match the search term 'al' in any part of the string. For example, using search('al') will return results, whereas the exact match function would require search('alice') to be successful.

const users = [{
    "username": "Alice",
    "firstName": "Alice-U",
    "lastName": "Wonderland"
  },
  {
    "username": "bob",
    "firstName": "Bob-u",
    "lastName": "Builder",
  },
  {
    "username": "charly",
    "firstName": "Charly-u",
    "lastName": "Brown",
  }
]

function searchFull(term) {
  return users.filter(({
    username,
    firstName,
    lastName
  }) => {
    return username.toLowerCase() === term.toLowerCase() ||
      firstName.toLowerCase() === term.toLowerCase() ||
      lastName.toLowerCase() === term.toLowerCase()

  })

}


function search(term) {
  return users.filter(({
    username,
    firstName,
    lastName
  }) => {
    return username.toLowerCase().indexOf(term.toLowerCase()) > -1 ||
      firstName.toLowerCase().indexOf(term.toLowerCase()) > -1 ||
      lastName.toLowerCase().indexOf(term.toLowerCase()) > -1

  })

}

console.log(searchFull('alice'))
console.log(search('al'))

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

Tips for delaying the opening of the file chooser for an input type file until after receiving the http request's response

My web page includes a file chooser. <input type='file' id='xxx'> When this input is clicked, I need to validate other fields using an HTTP request. What I am looking for is a way to make the file chooser wait until I receive th ...

Show representation in UTF-8 character set

In order to display my model in JSON format, I am using: @Html.Raw(Json.Encode(Model.Events)) My server-side model looks like this: {"Title":"Party","Url":"site.com/events?id=1&view=table"} However, on the client side, the JSON appears as: {"Title ...

The main page's navbar dropdown menu fails to appear after a certain length

I've encountered a strange problem with my navbar. I utilized an online template, and the issue is that on the main page, the dropdown menu doesn't extend fully; it only goes as far as the length of the navigation bar (Refer to the image below). ...

What is the best way to retrieve the props from server-side rendering when re-rendering the component on the client side?

After conducting extensive research, I have been unsuccessful in getting it to function properly. My project is built on express.js and react in an isomorphic application setup. To generate my component and send it back to the client side, I utilized ren ...

Having trouble with fetch() not working in Next.JS while securing API Routes with auth.js

Currently, I am working on a project that involves user authentication using auth.js in next.js. The main goal is to create an API that retrieves specific user information from a MongoDB Database. The website itself is secured with middleware in next.js. I ...

Determine the character count of the text within an *ngFor loop

I am a beginner in Angular (8) and I am trying to determine the length of the input value that I have created using a *ngFor loop as shown below: <div *ngFor="let panel of panels; index as i" class="panel" [id]="'panel-' + panel.id"> & ...

How can you display variables within another variable in Vue?

Is it possible for Vue to render variables inside another variable? If not, how can I achieve this functionality? data() { return { SQL: { columns: ["id", "status", "post"], table: "users", limit: 10, query: "SELECT {{co ...

Exploring Binary Search Functionality in Python

So here's an issue I'm facing. The task at hand involves finding a pit within a given landscape represented by a non-empty one-dimensional array called seq. A cell at index i is considered a pit if its value (seq[i]) is less than or equal to ...

What is the rationale behind using both useMemo and createSelector in this code?

This example from the React-Redux documentation showcases how a selector can be utilized in multiple component instances while depending on the component's props. import React, { useMemo } from 'react' import { useSelector } from 'reac ...

Trouble arises when accessing GET form in php/Ajax

I am in the process of creating a dynamic website. At the top, I have an input form that, when submitted, should display the output from an asynchronous request to a PHP page using echo to show what was submitted. Unfortunately, it's not functioning ...

"Recall the act of pressing a button on a

Is there a way to make my website remember if the mute button was pressed? Currently, the website plays music with a mute button, but it doesn't retain the mute setting when navigating to a new page or refreshing the current page. The local storage sc ...

Dealing with Redis session management in the event of a database disconnection

Having trouble with losing connection to Redis, which is used for sessions in my Express App. var RedisStore = require('connect-redis')(express); sessionStore = new RedisStore(config.db.redis.connection); sessionStore.client.on('error' ...

What is the best way to construct a collection of this specific data structure and transmit it using socket.io?

I am currently using node.js along with socket.io in my project. Within my MySQL table, I have the following data structure: TABLE USERS: Id: 1, Name: 'ABC1', ToUserId: 1 Id: 2, Name: 'ABC2', ToUserId: 1 Id: 3, Name: &apos ...

Enhancing the appearance of input range sliders using before and after elements for custom styling

I'm looking to create something similar to the image linked below https://i.sstatic.net/Czef9.png Note:: The above image features a V-shaped icon, which is what I'm aiming for. Currently, I am utilizing input[type="range"]. The foll ...

The system is unable to locate the module at 'C:UsersSanjaiAppDataRoaming pm ode_modulesprotractorinprotractor'. This error originates from internal/modules/cjs/loader.js at line 960

After running "protractor conf.js" without any issues, I decided to install protractor globally using the command "npm install -g protractor". However, after installing protractor globally, I encountered the following error message: internal/modules/cjs/lo ...

Exploring the depths of web automation using Python and Selenium, harnessing the power of a while

Currently, I am navigating through various pages on iens website using Selenium and Python. My goal is to click on the "Volgende" button (which means "next" in Dutch) continuously until there are no more pages left by implementing a while loop. Specificall ...

Can you explain the concept of a read-only property in JavaScript and its significance?

I'm a bit puzzled about the concept of a read-only property. While MDN defines classList as such, can you clarify what this really entails? ...

In React Native, it is not possible for one function to be executed inside another function

When clicking on a button, I have two functions that need to be executed: this.state = { myLimit: this.props.limit.lim, modalOpen: false, } submit = () => { // Send state to Redux reducer let lim = {'lim':this.state.my ...

Tips for resolving issues with mysql_fetch_assoc()

Similar Question: mysql_fetch_array() error - Fixing parameter issue Whenever I execute the code below, I encounter this issue: Warning: mysql_fetch_assoc(): provided argument is not a valid MySQL result resource If anyone knows how to rectify this pro ...

Issue TS2307: Module 'fs' or its type declarations cannot be located

I'm having trouble importing the fs module into my TypeScript component using import * as fs from 'fs'; I need it to use the writeFile method, as I want to extract data from an HTML form and write it to a JSON file. However, I am getting t ...