Find all elements within JSON data using lodash.js

Hello friends, I'm dealing with a JSON object:

  var companies = [
    { id: 1, name: "Test Company", admin: "Test Admin" },
    { id: 2, name: "Another Company", admin: "Test Admin", country: 'Spain' },
    { id: 3, name: "New Company", admin: "Admin 4" },
    { id: 4, name: "Free Company", admin: "Jhon Miller", city: 'New York' }
];

I am in the process of creating a function to return a new JSON with elements based on specific filters passed as parameters. So far, I've created a simple function like this:

   function searchItems(companies, filter) {
    var result;
      if (typeof filter === "undefined" ||  filter.length == 0) {
          result = companies;
      } else {
        result = _.filter(companies, function(c) {
         return _.includes(_.lowerCase(c.name), _.lowerCase(filter));
       });
     }
 }

The current function only allows filtering by the company name. My question is: how can I modify it to allow filtering by name, admin, country, and city but not by ID? For example, if the filter passed is 4, the function should return:

{ id: 3, name: "New Company", admin: "Admin 4" }

Or if the filter is "iLl", it should return:

{ id: 4, name: "Free Company", admin: "Jhon Miller", city: 'New York' }

Thank you!

Answer №1

The search functionality below utilizes the filter() method to extract matching objects based on the inputted text. To determine if an object qualifies as a match for the searched text, we employ the some() function against all values within each object in the collection. The some() operation checks each value in the object in lowercase format against the lowercase version of the searched text using includes().

It should be noted that I opted for toLower() over lowerCase() since the latter converts a string into lowercase form considering separate words, while the former completely transforms the entire string disregarding its case format -- you can modify this choice based on your specific requirements.

An update: I have included an exclude parameter to enable omitting() certain properties when evaluating object values against the entered text.

function filterByText(collection, text, exclude) {
  text = _.toLower(text);
  return _.filter(collection, function(object) {
    return _(object).omit(exclude).some(function(string) {
      return _(string).toLower().includes(text);
    });
  });
}
console.log(filterByText(companies, '4'));
console.log(filterByText(companies, 'iLl'));
console.log(filterByText(companies, '4', ['id']));

var companies = [{
    id: 1,
    name: "Test Company",
    admin: "Test Admin"
  },
  {
    id: 2,
    name: "Another Company",
    admin: "Test Admin",
    country: 'Spain'
  },
  {
    id: 3,
    name: "New Company",
    admin: "Admin 4"
  },
  {
    id: 4,
    name: "Free Company",
    admin: "Jhon Miller",
    city: 'New York'
  }
];

function filterByText(collection, text, exclude) {
  text = _.toLower(text);
  return _.filter(collection, function(object) {
    return _(object).omit(exclude).some(function(string) {
      return _(string).toLower().includes(text);
    });
  });
}

console.log(filterByText(companies, '4'));
console.log(filterByText(companies, 'iLl'));
console.log(filterByText(companies, '4', ['id']));
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

Below is an improved version of the aforementioned solution utilizing the partial() and flow() functions:

function filterByText(collection, text, exclude) {
  return _.filter(collection, _.flow(
    _.partial(_.omit, _, exclude),
    _.partial(
      _.some, _,
      _.flow(_.toLower, _.partial(_.includes, _, _.toLower(text), 0))
    )
  ));
}

console.log(filterByText(companies, '4'));
console.log(filterByText(companies, 'iLl'));
console.log(filterByText(companies, '4', ['id']));

var companies = [{
    id: 1,
    name: "Test Company",
    admin: "Test Admin"
  },
  {
    id: 2,
    name: "Another Company",
    admin: "Test Admin",
    country: 'Spain'
  },
  {
    id: 3,
    name: "New Company",
    admin: "Admin 4"
  },
  {
    id: 4,
    name: "Free Company",
    admin: "Jhon Miller",
    city: 'New York'
  }
];

function filterByText(collection, text, exclude) {
  return _.filter(collection, _.flow(
    _.partial(_.omit, _, exclude),
    _.partial(
      _.some, _,
      _.flow(_.toLower, _.partial(_.includes, _, _.toLower(text), 0))
    )
  ));
}

console.log(filterByText(companies, '4'));
console.log(filterByText(companies, 'iLl'));
console.log(filterByText(companies, '4', ['id']));
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

Answer №2

Unlocking the power of Object.keys()
is the key to success ;)

Give this a shot :

var companies= [
    { id: 1, name: "Test Company", admin: "Test Admin" },
    { id: 2, name: "Another Company", admin: "Test Admin", country: 'Spain' },
    { id: 3, name: "New Company", admin: "Admin 4" },
    { id: 4, name: "Free Company", admin: "Jhon Miller", city: 'New York' }
];

function searchBooks(filter){
    var result;
      if (typeof filter=== "undefined" ||  filter.length==0) {
          result = companies;
      } else {
        result = _.filter(companies, function (c) {

         // This part will transform every property value in a single string.
         var searchIn = Object.keys(c).reduce(function(res, val) { return (val !== 'id')?res+c[val]:res }, '');
         return _.includes(_.lowerCase(searchIn),_.lowerCase(filter));
       });
     }
     console.log(result)
 }
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
<input type="text" onKeyUp="searchBooks(this.value)">

Answer №3

Is it possible to search through all properties in the same manner, by specifying your desired keys for searching? Check out searchBooksSpecificProperties

Alternatively, if you wish to search through all fields every time, you can obtain the keys for each item using _.keys(), as demonstrated in searchBooks

var companies= [
    { id: 1, name: "Test Company", admin: "Test Admin" },
    { id: 2, name: "Another Company", admin: "Test Admin", country: 'Spain' },
    { id: 3, name: "New Company", admin: "Admin 4" },
    { id: 4, name: "Free Company", admin: "Jhon Miller", city: 'New York' }
];

function searchBooks(companies, filter){
  var result;
    if (typeof filter=== "undefined" ||  filter.length==0) {
        result = companies;
    } else {
      result = _.filter(companies, function (c) {
        var cProperties = _.keys(c);
        _.pull(cProperties, 'id');
        return _.find(cProperties, function(property) {
          if (c[property]) {
            return _.includes(_.lowerCase(c[property]),_.lowerCase(filter));
          }          
        });         
     });
   }
   return result;
 }

 console.log('searchBooks:');
 console.log(searchBooks(companies, 'Admin 4'))
 console.log(searchBooks(companies, 'York'))
 
function searchBooksSpecificProperties(properties, companies, filter){
  var searchSpecificProperties = _.isArray(properties);
  var result;
    if (typeof filter=== "undefined" ||  filter.length==0) {
        result = companies;
    } else {
      result = _.filter(companies, function (c) {
        var cProperties = searchSpecificProperties ? properties : _.keys(c);
        return _.find(cProperties, function(property) {
          if (c[property]) {
            return _.includes(_.lowerCase(c[property]),_.lowerCase(filter));
          }          
        });         
     });
   }
   return result;
 }
 console.log('searchBooksSpecificProperties:');
 console.log(searchBooksSpecificProperties(['name', 'admin'], companies, 'Admin 4'))
 console.log(searchBooksSpecificProperties(['name', 'admin'], companies, 'York'))
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

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

Step-by-step guide on sorting WordPress posts by a custom field date

I've created an event sidebar section that will only show the next 3 upcoming events. I have successfully set up the custom post type and custom fields, but I am struggling to figure out how to order the posts based on the start date of the events, wh ...

How can I trigger a method after the user has finished selecting items in a v-autocomplete with multiple selection using Vuetify?

After multiple selections are made in a v-autocomplete, I need to trigger a method. However, the @input and @change events fire after each selection, not after the full batch of selections. Is there an event that triggers when the dropdown menu closes? Al ...

What are some ways to create a responsive image design?

Currently, I am using the code below to enlarge an image when clicked on. I have attempted using media queries in CSS... I have also added another class in #modalPopupHtml# to adjust the size of the large image: .imgsize{ height: 600px; width: 800px; ...

Display or conceal a div element depending on the user's choice

I am looking to hide inactive divs, but whenever I reload the page, all tab contents merge into one. The screenshot below shows the issue I'm facing. Screenshot Below is the code snippet: $('.tab a').on('click', function ...

Make sure the page preloader is visible before any other content is loaded

Currently, I am working on a straightforward preloader page that remains visible until the main content of the page is completely loaded. Despite the functionality of the loading page, my main concern lies in the quick display of the main content before th ...

Transform a string (variable) into an object using JSON.parse, encountering an unexpected token error

I am struggling with parsing a string variable back to an object. Despite searching through various posts on this issue, I have not found a solution that works for me. if(subMatch.match(/\{.*\}/)){ /// new Object of some sort var o ...

Using opening and closing curly braces within a PHP foreach loop

I am facing an issue with formatting an array in PHP. The array structure is as follows: Array ( [0] => Array ( [team1_score] => 10 [team2_score] => 5 [round_number] => 1 [teamtitle1] ...

If an iframe contains a div with a particular class inside, then execute the following code

I need to dynamically add a class to the parent element if a specific class is present in its child. The issue: the content is within an iFrame and I'm not very proficient with jQuery. It doesn't necessarily have to be jQuery, any alternative m ...

Set up your Typescript project to transpile code from ES6 to ES5 by utilizing Bable

Embarking on a new project, I am eager to implement the Async and Await capabilities recently introduced for TypeScript. Unfortunately, these features are currently only compatible with ES6. Is there a way to configure Visual Studio (2015 Update 1) to co ...

Having trouble getting the video to load on your Mozilla Firefox browser?

Unable to play video on Firefox. Error message: URL.createObjectURL(video): Error decoding media resource blob: NS_ERROR_DOM_MEDIA_FATAL_ERR (0x806e0005) Details: Decoder may not support the requested video format with YUV444 chroma subsampling. Tried usi ...

What is the best way to implement OTP expiration time in Next.js using Firebase?

Could anyone please help me with setting the OTP expire time in Next.js using Firebase? I have searched through the Firebase documentation but haven't been able to find a solution to my issue. Below is the code I am using to send the OTP: const appV ...

Ajax fails to transfer the complete data

I am currently facing an issue with my request. Here is the code snippet that I need help with: logInWithFacebook = function() { FB.login(function(response) { if (response.authResponse) { FB.api('/me', {fields: 'name,email,location,p ...

PHP - Issue with AJAX Login Functionality

I have been developing an AJAX login system and encountering an issue where it does not send any response back unless I use exit("error here") in the script. However, my goal is to return a JSON response instead. The form structure: <div id="account" ...

What steps should I take to troubleshoot the 'TypeError: userId is not a function' error in my unban feature?

I am currently working on implementing an unban feature for my bot, however, I am encountering issues whenever I try to test the command (!unban <userId>). Instead of the expected outcome, I am faced with an error which is detailed below. This snipp ...

What could be causing the issue with my Mongoose One-To-Many Relationships not linking correctly?

Can anyone shed light on why the connection between "users" and "posts" (where users can have multiple posts) is failing to work properly? Despite setting up my mongoose associations correctly, when a new post is made, it doesn't get assigned to a use ...

Utilize a web service within a service file and leverage it across multiple locations

I am seeking help with reusing a service function in different parts of my app, specifically to display a certain parameter ('title') in the HTML template. Firstly, I created a service: import { Injectable } from '@angular/core'; impo ...

Guide on how to toggle disabled input text box upon checking checkbox using JavaScript

When the checkbox next to the appended text box is checked, I want to disable that text box. The hard-coded text box is already disabled when its checkbox is checked. You can see the actual outcome by running the code snippet or check out the screenshots b ...

generating a new item using Mongoose searches

How can I generate an object based on queries' results? The table in the meals operates using database queries. How do I handle this if the queries are asynchronous? const getQueryResult = () => { Dinner1300.count().exec(function (err, count) ...

Display information in real-time based on user input using Highcharts

I am trying to display data using highcharts on my index.php page. Can anyone help me with this?, here is what I have attempted so far: This is the HTML code I have: <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" cont ...

A guide on retrieving bytecode from a specific PDF using Angular

Can anyone help me with extracting the bytecode from a selected PDF file to save it in my database? I keep encountering an error stating that my byte is undefined. Could someone please review my code and identify what might be causing this issue? I attemp ...