What's the best way to dynamically filter an array with a mix of different object structures?

Within my data, I have 6 different types of objects (some with double nested arrays), with varying numbers of entries, as long as each entry is unique.

These objects do not possess a consistent unique identifier (one is applied on submission in the backend).

Here is an example array with 2 object types:

arr = [
    {name:"aaa",time:15},
    {name:"aaa",time:22},
    
    {timeline: "250", chars[{a},{b},{c}]},
    {timeline: "220", chars[{d},{e},{f}]},
]
    
obj = {name:"aaa",time:22}

My goal is to determine if obj exists in arr, resulting in a true or false output.

I have attempted the following methods:

  1. I received a recommended method that resulted in an error:
     #<Object> is not a function
console.log(arr.find(obj))
  1. Another suggestion I found always returns false, even when the element is present
console.log(arr.includes(object))
  1. My personal attempt at a method always fails.
console.log(arr.filter((element, index) => element === obj)

Regarding attempt 4, comparing only the name field is inadequate as it overlooks unique times essential for valid entries.

Providing every field for comparison would not work either, as each object may or may not have certain fields, leading to errors.

Manually pre-filtering into distinct categories is impractical, as each new type added would require manual inclusion in the filter.

If you are aware of a library that can handle this, please share, as it would be ideal. Alternatively, any other suggestions (excluding separating arrays) are welcome.

Answer №1

Utilize arr.some() to verify if the specified object exists within the array.

A convenient method to compare the objects is to stringify both Objects and then compare them.

const arr = [
    {name: "aaa", time: 15},
    {name: "aaa", time: 22},
    {name: "aaa", chars: ["a", "b", "c"]},
    {name: "bbb", chars: ["d", "e", "f"]},
]

const obj1 = {name: "aaa", time: 15}
const obj2 = {name: "aaa", chars: ["a", "b", "c"]}

console.log(arr.some((element) => JSON.stringify(element) === JSON.stringify(obj1)))   // true
console.log(arr.some((element) => JSON.stringify(element) === JSON.stringify(obj2)))   // true

Performance considerations were not taken into account.

Answer №2

I didn't focus much on performance in this solution, but it could be helpful:

function findObjectInArray(arr, obj) {
  const result = arr.some((element) => compareObjects(element, obj));
  console.log(result);
}

function compareObjects(obj1, obj2) {
  if (Object.keys(obj1).length !== Object.keys(obj2).length) return false;
  for (let property in obj1) {
    if (!obj2.hasOwnProperty(property) || obj2[property] !== obj1[property]) {
      return false;
    }
  }
  return true;
}

You can use this function like this:

array = [
  { name: "aaa", time: 15 },
  { name: "aaa", time: 22 },

  { timeline: "250", data: ["2", "3", "4"] },
  { timeline: "251", data: ["2", "3", "4"] },  // what is chars[{d},{e},{f}] ?!
];

object = { name: "aaa", time: 22 };

findObjectInArray(array, object);

Answer №3

Issue : The variable arr does not contain a valid array. The nested chars does not have a valid value.

Resolution : To address this issue, you can convert the JSON object into a JSON string and compare the values.

This approach is effective when searching for a single object within the arr array.

Check out the Live Demo below:

const arr = [
    {name:"aaa",time:15},
    {name:"aaa",time:22},  
    {timeline: "250", chars: [{a: 1},{b: 2},{c: 3}]},
    {timeline: "220", chars: [{d: 4},{e: 5},{f: 6}]},
];
    
const obj = {name:"aaa",time:22};

const res = JSON.stringify(arr).indexOf(JSON.stringify(obj)) !== -1 ? true : false;

console.log(res);

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

JavaScript functions triggered upon page reload or refresh

How can I trigger a function from a FireFox extension/GM Script every time a page reloads or refreshes? Imagine this scenario: I visit a website that prompts for a username and password. My code fills in the credentials and submits them. The page reload ...

Activate an event on a shadow DOM element that is covered by an element in the light DOM (not directly related)

I am currently facing a challenge in retrieving the coordinates of a table cell within a shadow DOM. This table cell may have overlay elements displayed above it, which could span over multiple cells and may not necessarily be direct children of the cell I ...

Is there a way to automatically restart my Gulp task when I save changes?

I have a series of Gulp tasks in version 4 that handle tasks like compiling Webpack and Sass, optimizing images, etc. These tasks are automated through a "watch" task while I am working on a project. However, when my watch task is active, saving a file tr ...

Achieving two-way data binding using a Service in AngularJS - Step by step guide

Searching a JSON file, extracting data to create a table, and continuously monitoring for updates to display in real-time is a challenging task. Despite multiple attempts with AngularJS, achieving this has been elusive. Below is the code snippet: app.js ...

Utilize the return value within a .map function following the completion of a request.get call

Essentially, for security reasons, I need to convert an image from a URL to base64. Currently, I have two functions in place. One function is responsible for converting the image from the URL to base64, and the other function is iterating over the databas ...

Transform the constant character pointer into an integer array

Currently, I am experimenting with the C++ MongoDB driver Below is the code I am testing: http://pastebin.com/eQUekQU2 In the code, I create a small integer array and store it in the mongo database as binary data. To retrieve the binary data while loop ...

Utilizing Ajax to Populate a Dropdown List with Data

Currently, I am retrieving data from an API. The data consists of IDs and charity names that need to be displayed in a dropdown list. While I have successfully shown the charity names in the dropdown list, I am struggling with including the IDs. How can I ...

Controlling the Quantity of Selected Checkboxes with JavaScript

I am facing an issue with implementing multiple checkboxes with limits in JavaScript, as shown below. $(".checkbox-limit").on('change', function(evt) { var limit = parseInt($(this).parent().data("limit")); if($(this).siblings(':checked&ap ...

Avoid filling the container with an excessive amount of grids while maintaining the correct aspect ratio

I encountered a situation where I needed to dynamically create a grid with square grids of dimensions MxN. Below is the code snippet for achieving this: rerender = (event) => { const height = document.getElementById("y-input").value; const width ...

Using Angular's ngBlur directive on multiple input fields

My current task involves capturing and saving all content on a webpage after it has been edited. For example, when a user clicks into an input field, enters data, and then clicks elsewhere, I would like to trigger a function to collect all the model data a ...

Testing the functionality of an Express.js application through unit testing

I'm currently working on adding unit tests for a module where I need to ensure that app.use is called with / and the appropriate handler this.express.static('www/html'), as well as verifying that app.listen is being called with the correct p ...

Issue: `Alert` not triggering after clicking on anchor link in AJAX response

Below is the code I am currently working with: $('.ver').click(function(e) { e.preventDefault(); var id = $(this).next().val(); $.post('cotizar_detalles.php', {'id': id}) .done(function(response) { ...

Transforming class attributes in Typescript

I am facing a situation where I need to alter the type of a variable that stores an object based on certain conditions. Here is the variable in question: class MyClass { public referrers: SelectItemGroup[]; } The issue arises when I only need to add a ...

What's the best method for concealing components: using a class to hide or removing them from the

I am encountering difficulties in React as I try to add a class to a component after a specific time duration. My goal is to apply the "hidden" class to a loading image, changing it to display: none after a few seconds. However, despite my efforts, I keep ...

Routes inoperative as intended

When using a standard expressroute for this login, I have noticed that even if the req.body.password is incorrect, I am still getting redirected to '/login'. router.post('/student/login', (req, res) => { if (req.body.password === ...

Utilizing react hooks to sort through information

Hey everyone, I've been diving into React for a few weeks now so please bear with me =). I encountered an issue with my filter function when switching from using dummy data to fetching data from a Django API. The filter does work, but the data disappe ...

What steps should I take to fix the error I'm encountering with React Material UI

import { AppBar, Toolbar, Typography } from '@material-ui/core' import React from 'react' import { makeStyles } from '@material-ui/styles'; const drawerWidth = 240; const useStyles = makeStyles((theme) => { return { ...

Unable to extract query parameters from URL using Express JS as req.query returns an empty object

I came across discussions about this issue here and here, but unfortunately, the solutions provided didn't work for me. I'm attempting to extract parameters from the URL using req.query. In my server.js file, I've implemented the following: ...

What is the best way to utilize jquery .grep() for searching and modifying an object?

I am working on a straightforward algorithm that involves retrieving an object from a jQuery key/value array, making some updates to it, and then replacing the original object within the array with the updated one. Can anyone guide me on how to accomplish ...

Setting the iDisplayLength property in jQuery Datatables to -1 will display all rows in the table

Using jQuery Datatables, I am trying to populate a table with entries from a server via ajax. The data retrieval works perfectly, and I am able to display them in the table. However, I am facing an issue where I want to show all rows/entries at once. I hav ...