Iterate through a collection of nested objects and check them against an object contained within an array

I'm facing a frustrating issue in Firebase where I am required to compare an object returned to me with an array.

I need assistance in completing this method:

const removeAlreadySeenUsersFromQueue = (newUsers, likedUsers) => {

}

The scenario is that newUsers is an array of objects, each containing an id of interest.

On the other hand, likedUsers is returning as an array of objects within objects, like so:

[{object1: {}, object2: {}, object3: {}]
, essentially an array of length one. Within each object, there exists an id key that I need to identify. My goal is to compare both arrays and return an array solely containing objects whose ids appear only in newUsers and not in likedUsers. I believe object.keys() might be useful here, but my current attempts are unsuccessful

For example:

[{id: 4444}, {id: 5555}, {id: 6666}]

[{object1: {id: 4444}, object2: {id: 5555}, object3: {id: 121241}}]

After comparing these two arrays, I expect to receive just {id: 6666}.

Answer №1

This code snippet is designed to handle multiple matches by filtering out elements from one array that match certain criteria in another array. For demonstration purposes, an additional object with the id value of 7777 has been added to the first input array.

// Input arrays
var array1 = [{id: 4444}, {id: 5555}, {id: 6666}, {id: 7777}];
var array2 = [{object1: {id: 4444}, object2: {id: 5555}, object3: {id: 121241}}];

// Output array after filtering
var newArray = array1.filter(function(obj) {
    // Assume the element from array1 should be added by default
    var includeElement = true;

    // Check if the element from array1 exists in array2 and update includeElement accordingly
    Object.keys(array2[0]).forEach(function(key) { 
        if (array2[0][key].id == obj.id)     
            includeElement = false; 
    });

    // Complete the filter function by returning whether to include the element or not
    return includeElement;
});

// Log the filtered output array
console.log(newArray);

Answer №2

To retrieve the ids, you can utilize the reduce method and then apply the filter function in combination with the some function.

The result of the reduce operation may contain duplicate elements like [666, 555, 666, 777], but this scenario is not considered since your example does not involve repeated ids.

var source = [{ id: 4444 }, { id: 5555 }, { id: 6666 }, { id: 123456 }];
var content = [{ object1: { id: 4444 }, object2: { id: 5555 }, object3: { id: 121241 }}];

var ids = content.reduce((acc, curr) => [...acc, ...Object.keys(curr).map((k) => curr[k].id)] , []);

var result = source.filter((e) => {
  return !ids.some((c) => {
    return e.id === c;
  });
});

console.log(result);

Resources

Answer №3

Did you mention that your array has a length of 1? So, essentially, you're referring to something like [{}]? Why not consider changing it to [{}, {}, {}] and then looping through it using the for (element of array) - for of loop. Alternatively, if you prefer having all elements within one object, you can iterate over it using a for in loop by going with for (element in array[0]).

UPDATE Upon seeing your example, I've come up with this snippet:

const firstArray = [{id: 4444}, {id: 5555}, {id: 6666}];
const secondArray = [{object1: {id: 4444}, object2: {id: 55555}, object3: {id: 121241}}];

for (let object in secondArray[0]) {
   if (firstArray.some(el => el.id === secondArray[0][object].id)} {
      //perform some action
   }
}

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

Run a series of functions with arguments to be executed sequentially upon the successful completion of an ajax request

I am currently working on implementing a couple of jQuery functions to assist me in testing some api endpoints that I am developing in php. While I have limited experience with Javascript and jQuery, I am struggling to figure out what additional knowledge ...

Having trouble persisting my login status in Selenium using Python

Has anyone experienced issues with logging into Instagram using an automate tab? Previously, I didn't have any problems, but now it seems that Instagram is not allowing users to log in through automation. An error message stating the following appears ...

How to dynamically increase vote tallies with React.js

The voting system code below is functioning well, displaying results upon page load. However, I am facing an issue where each user's vote needs to be updated whenever the Get Vote Count button is clicked. In the backend, there is a PHP code snippet ...

Automatic button rotation

I managed to set up a button that works on click with a delay, making it semi-automatic. However, I'm struggling with getting it to not pause after just one click. Here's what I have so far: <!DOCTYPE html> <html> <body> &l ...

Unable to click, but can only be activated by touchstart or mousedown

Is it possible to bind a 'click' event to a paragraph? Here is the function I am using: $(document).on('touchstart mousedown',"p span.text", function(e) { console.log('I was clicked'); *more code here* }); When I ...

PHP is spitting out json that is not valid

I am facing an issue with the PHP code below, as it is returning an invalid JSON error and I am unsure of the reason: <?php include("dbConnect.php"); $sql = "SELECT QID, Question, Answer,CatID FROM Questions"; $res = mysqli_query($con,$sql); $result ...

When the input CTRL+C is entered in the console, Node.js / JavaScript will output

I have a script that I use to restart another script. Here is the code snippet: catch(err){ console.log(err) webhook.send(`Error monitoring **www.-.com**, restarting monitor.`) await browser.close() await sleep(monitorDelay) return chec ...

Error: Unable to locate module: Unable to resolve './Page.module.css' in Next.js version 13

When I run npm run build on Vercel and Heroku, I encounter an error that does not occur on my local computer: The error message is Module not found: Can't resolve './Page.module.css' I am trying to import this file from app/page.tsx, and b ...

Avoid the need to refresh the HTML content every time there is a change in the Angular $

One of the challenges I'm facing is with a for loop in my JavaScript: for (var i=0;i<2;i++) { $scope.widget = widgets[i]; $scope.header = widgets[i].data.header; $scope.items = widgets[i].data.items; $scope.footer = widgets[i].data ...

Reloading a page in Vue-Router after submitting a form

Learning Vue by creating a movie searcher has been quite challenging. The issue I'm facing is that I'm using the same component for different routes with path params to fetch specific information. However, when I submit a form with a query for t ...

Using jQuery to organize object properties based on the value of another property

Within my collection, I have an array of objects structured as shown below. [ {"rel_id": 1,"forward_flag": true,"asset_id":5,}, {"rel_id": 1,"forward_flag": true,"asset_id":8}, {"rel_id": 1,"forward_flag": false,"asset_id":3}, {"rel_id": 2,"forwar ...

Replace the image with text inside an anchor when the anchor is being hovered

I want a logo (we'll call it .item-logo) to be shown inside a circle when not being hovered over, but when you hover over the container, the date should be displayed. Here is the HTML code: <div id="main-content" class="container animated"> ...

Ensuring a response is sent back only after a loop has completed in NodeJs

Struggling to properly format the logic in order to send back a fully populated array of objects after a GET request to a specific URL. The goal is to take the "connections" array from the user making the request, extract the connection's name and pic ...

Issue with unit testing in Firestore: Anticipated data type was supposed to be 'DocumentReference', however, what was received was a unique Firestore object

I am trying to execute unit tests for Firestore. Below is the code snippet I am using: import { getDoc, setDoc } from "@firebase/firestore"; import { assertFails, assertSucceeds, initializeTestEnvironment, RulesTestEnvironment, } from &qu ...

How to Extract an Object from an Array using React

I have a situation where I am fetching data from an API using axios. Specifically, on my invoice details page, I am trying to retrieve data for only one invoice using the following code: const id = props.match.params.id; const invoice = useSelecto ...

Is there a way for me to loop through the URLs stored in an array and showcase them individually in an iframe?

This code snippet aims to iterate through a list of URLs and display the latest one in an iframe. It also incorporates jQuery's countdown plugin for additional functionality. <?php $count=0; $urls[]="http://www.techcrunch.com"; $urls[]="http://www ...

Updating switch data on click using Vuejs: A step-by-step guide

Could someone please explain to me how to swap two different sets of data when clicked? For instance, let's say we have the following data: data() { return { data_one: [ { name: "Simo", ...

What is the best way to utilize an HTML form for updating a database entry using the "patch" method?

I have been attempting to update documents in my mongoDB database using JavaScript. I understand that forms typically only support post/get methods, which has limitations. Therefore, I am looking for an alternative method to successfully update the documen ...

Animation not fluid with ReactCSSTransitionGroup

Currently, I am in the process of developing an image carousel that showcases images moving smoothly from right to left. However, despite its functionality, there seems to be a slight jaggedness in the animation that I can't seem to resolve. Interesti ...

The output displayed is showing the result of an Ajax request as `[object HTML

When I attempt to retrieve data using ajax, the output displays as [object HTMLInputElement]. Is there a way to convert this object to a string? Below is my JSP code which utilizes ajax: $('select#product').change(function() { var para ...