Mastering the art of filtering object arrays with underscoreJS

(PROBLEM SOLVED! Check the solution in the responses)

Here's my query:

I am trying to filter an array of objects based on a specified object, but all my attempts have resulted in an empty array. I suspect that the issue lies in iterating over an array of objects rather than a simple array.

Below is the code snippet where I am facing this challenge:

I have included an example using UnderscoreJS for filtering

(Click on the button to view the outcome)

$(document).ready(function() {

  /*
   *   BEGIN - Custom Filter using Underscore.js
   *
   */
  var arrObject = [{
    "data": [{
        "img": "test1"
      },
      {
        "img": "test2"
      },
      {
        "img": "/image_folder/sub_folder/886.jpg"
      }
    ]
  }];

  var compare = [{
    "img": "/image_folder/sub_folder/886.jpg"
  }];

  var finalArray;

  $.each(arrObject, function(index, element) {
    finalArray = _.filter(element.data, function(ev) {
      return ev == compare;
    });
  });

  console.log(finalArray);

  /*
   *   END - Custom Filter using Underscore.js
   *
   */

  /*
   *   START - Original Filter from Underscore.js Documentation
   *
   */
  $(document).on("click", ".originalUnderscore", function() {
      var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) {
      return num % 2 == 0;
    });
    console.log(evens);
  });
  /*
   *   END - Original Filter from Underscore.js Documentation
   *
   */

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

<button class="originalUnderscore">Click to show the original filter</button>

Answer №1

It is important to use _.isMatch(...) when comparing objects because === only compares references.
Additionally, there was a mistake in your code where you were comparing an object element.data[0] with an array compare.

Your corrected code should look like this :

$(document).ready(function() {
  const arrObject = [{
    "data": [{
        "img": "test1"
      },
      {
        "img": "test2"
      },
      {
        "img": "/image_folder/sub_folder/886.jpg"
      }
    ]
  }];

  const compare = {
    "img": "/image_folder/sub_folder/886.jpg"
  };

  $('.filterBtn').on('click', () => {
    let filtredArray = [];
    $.each(arrObject, (index, element) => {
      filtredArray = _.filter(element.data, function(ev) {
        return _.isMatch(ev, compare);
      });
      console.log(`filtredArray from data in element at index ${index}`);
      console.log(filtredArray);
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

<button class="filterBtn">Click filter</button>

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

String Replacement in JavaScript

Here's the scenario: I have a string var str="abc test test abc"; Is there a way to specifically replace the second occurrence of "abc" in the string using the str.replace() method? ...

JavaScript - Removing Content from an Element

I have a coding script that adds an image preview of uploaded images. The issue I am facing is that the previous image does not clear when the form is filled out again. The id of the div where thumbnail images are being displayed is "thumbnail". Can someo ...

Unable to retrieve DateTime.Now as a string within a Razor view

I am trying to retrieve the current time in a Razor View and utilize it in JavaScript, as demonstrated below: @{ string fileName = "Score_List_" + DateTime.Now.ToShortDateString(); } <script> // assigning C# variable to JavaScript variabl ...

There was an error during module build process: ReferenceError occurred due to an unrecognized plugin "import" specified in "base" at position 0

I have encountered an error while working on my ReactJS project using create-react-app. The error arose after I added and removed a package called "react-rte". Now, every time I try to start my project, I get the following error: Error in ./src/index.js Mo ...

Error Message "Alexa.create is not a valid function" encountered while using the Alexa HTML Web API on the Echo Show 10

Here is the HTML code for my custom Alexa Skill. <head> <script src="https://cdn.myalexaskills.com/latest/alexa-html.js"> </script> </head> <body> var alexaClient; Alexa.create({version: '1.0'}) .t ...

Locating the value of a data attribute from a distant parent div using jQuery

How can I access the closest div from an anchor tag that has a data-id attribute without using multiple parent() methods? Even though .parent().parent().parent() works, I am trying to find a better solution. <div class="panel panel-default" data-id="@ ...

Can you explain the significance of the declaration "char (* ( *f())[])();"?

While researching pointers to functions, I stumbled upon this intriguing declaration: char (* ( *f())[])(); I attempted to decipher the meaning behind it, but unfortunately came up empty handed... Can anyone shed some light on what this refers to? ...

JavaScript and .NET Core: Implementing file uploads without the use of FormData or FromFrom

Currently attempting to create a "basic" file upload feature. Utilizing JavaScript on the frontend and .NET Core on the backend. Previously, I had successfully implemented FormData / multipart, FromForm, and iFormFile. However, I have been advised agains ...

How can I make a function visible in function expressions when it's currently not showing up?

Here's a function expression that I have: var inputChecker = function(field) { return function() { if(field === '' || field === 'undefined' || field === null) { return false; } return true; ...

Retrieve the name of the file from a given URL by using JavaScript/jQuery, even when only the directory path is

I need to extract the current filename from the URL using: $currentFile = window.location.pathname.split("/").pop(); This method functions properly when the full path looks like: http://www.yoursite.com/folder/index.php It will return index.php, index. ...

Is there a way for me to incorporate a feature that verifies whether an email address is already registered before allowing the person to sign up?

I am currently working with Node.js, express.js, mongoose, and pug to develop a registration/login system. I have successfully stored the name and email in a mongoose database with specified schema for these fields. The data is sent from a pug page via a p ...

Converting a Curl command to a JavaScript POST request: best practices

Is it possible to convert the given curl code into a JavaScript post request that will function effectively in all browsers? curl https://connect.stripe.com/oauth/token \ -d client_secret=sk_test_f7PKXx5NRBFG5r41nTrPT7qB \ -d code="{AUTHORIZATIO ...

Issue with calling hooks. Hooks can only be invoked within the body of a function component

Looking to develop a todo application using React, but encountering an issue with the useContext hook. The error message "Invalid hook call..." suggests a few possible reasons for this problem: Possible mismatched versions of React and the renderer (e.g ...

The curious behavior of $viewContentLoaded in Angular

For my jQuery code, I wanted it to run immediately after the template view was loaded and the DOM was modified. To achieve this, I initially used the $viewContentLoaded event in my controller. $scope.$on('$viewContentLoaded', function(){ // ...

Is the scrolling functionality acting strange while using React Three Fiber?

In my React Three Fiber application, I have the following structure: Website Canvas NativeHTMLContent Canvas Website The issue I'm facing is that after scrolling down the entire canvas, the scrollbar resets to the top and starts scrolling from the t ...

Customize the theme of Ant Design for VueJS

I have successfully set up my Vue3 application with Tailwind and Ant Design. However, I am facing issues with customizing the Ant Design theme. I have been referring to this guide. When trying to customize the theme, I encountered the following error: Err ...

Is it possible to modify the color of a span element within a select dropdown?

Is there a way to change the color of a span to red within a select option in js fiddle? I am trying to modify the color of <span class="myError">This is a required field.</span> to red https://i.sstatic.net/nRF2c.png select{ color: green; ...

Locked first row and first column in HTML table

I'm struggling with freezing the first row and column in an HTML file exported from Microsoft Excel. When attempting to add position:fixed; to achieve this, I noticed that it changes the size and alignment of the headers. Can someone please advise me ...

How can I ensure security measures are in place to avoid XSS attacks on user-generated HTML content?

Currently, I am in the process of developing a web application that will allow users to upload entire web pages onto my platform. My initial thought was to utilize HTML Purifier from http://htmlpurifier.org/, but I am hesitant because this tool alters the ...

What is the reason behind the occurrence of an error when attempting to iterate through an array of objects within my react.js component?

Here is an example of some code: class Stepper extends Component { state ={ quiz_data: [ patient_data: [ {name: "A", age: "1"}, {name: "B", age: & ...