What is the best way to determine if an array of objects in JavaScript contains a specific object?

Here is some code that I am working with:

    let users = [];
users.push({
    username: "admin",
    password: "admin"
});
this.showAllUsers = function() {
    console.log(users);
};
this.addUser = function(user) {
    if('username' in user && 'password' in user) {
        users.push({
            username: user.username,
            password: user.password
        })
    }
    else {
        throw "Invalid object";
    }
};
this.isExist = function(user) {
    console.log(users.indexOf({
        username: "admin",
        password: "admin"
    }));

};

I am puzzled as to why the console log always prints -1. The users array does indeed contain an object with properties username: "admin" and password: "admin".

Answer №1

The method indexOf employs strict equality comparison (===). When using {foo: bar}, a new object is created that is unique and will not be strictly equal to any existing object in the array.

To solve this issue, you should iterate through the array and compare each object using deep equality. One way to achieve this is by utilizing the following function:

function checkMatch(arr, ref) { // Takes an array and a reference object
  return arr.filter(function (current) { // Selects items in the array...
    return Object.keys(ref).every(function (key) { // Where all keys...
      return ref[key] === current[key]; // Have the same values in both the item and the reference
    });
  });
}

Answer №2

Check out this helpful guide on using the indexOf method.
Also, always keep in mind that handling passwords on the client side can pose a serious security risk.

Answer №3

this.checkExistence = function(user) {
    console.log(users.indexOf({
        username: "admin",
        password: "admin"
    }));
};

The issue at hand is that you are verifying if the users array includes the newly created object. Since it's a new object, obviously it won't be included. You must verify if the users object contains any object with a username or password matching "admin". Perhaps, try something like:

this.checkExistence = function(user) {
    for(var x = 0; x < users.length; x++) {
        var current = users[x];
        if(current.username === user.username && current.password === user.password) {
            return true;
        }
    }

    return false;
};

Alternatively, you could utilize Linq.js, a library that greatly aids in such queries. It happens to be one of my personal favorites.

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

The value of `this` from React Store is currently returning null

I'm facing an issue where the this keyword is coming back as null in my store within a React component. I suspect that binding might be necessary, but I'm not entirely sure. Additionally, I am utilizing React Router and have the component wrapped ...

Can you help me transform this javascript code into a JSON format?

Is there a way for me to organize my data so that I have one main question with 5 choices, each associated with a vote? It's like thinking of it as a tree where the question is the root and has 5 leaves, representing the choices, and each choice furth ...

Increasing the token size in the Metaplex Auction House CLI for selling items

Utilizing the Metaplex Auction House CLI (ah-cli) latest version (commit 472973f2437ecd9cd0e730254ecdbd1e8fbbd953 from May 27 12:54:11 2022) has posed a limitation where it only allows the use of --token-size 1 and does not permit the creation of auction s ...

How can we transfer functions between files in JavaScript when creating a service library?

There's a piece of code located in my identity service that I'm working with. export function sumbitLogin(username, password) { console.log(username, password); } I want to simplify the process of accessing services in my components without ...

Animated jQuery carousel with a timer countdown feature

Currently, I am developing a jquery slider/carousel to display various promotions. I am seeking a method to indicate the time left until the next promotion appears. Similar to the flash promo on this website: Do you have any suggestions? ...

I am struggling to display the data fetched by Next.js on the page

I am struggling to display the data from the first file in my tanstack table or as a string within the HTML, even though I can see it in a console.log when grabbed by axios. The tanstack table worked fine with hardcoded data. In the console image provided, ...

What is the best approach for overlaying random meshes onto a terrain using a heightmap in three.js?

I'm interested in plotting randomly generated meshes at the y-position that corresponds to the terrain's height in three.js. While browsing through the documentation, I came across the raycaster method, which seems like it could be useful. Howeve ...

Tips on causing JavaScript execution to halt until an element has finished rendering

test.view.js timeDBox = new sap.ui.commons.DropdownBox({layoutData: new sap.ui.layout.GridData({linebreak: true}), change: function(oEvent){ oController.getKeyEqChart(); }, }), new sap ...

What is the process for activating and deactivating the scroll trigger within Material UI's useScrollTrigger module?

I'm currently working on setting up a survey page with Material UI in React. My goal is to have the survey questions appear when the user scrolls over them and disappear when they scroll out of view, similar to the behavior on this page. After some r ...

Utilizing Spiderable within Meteor results in the replication of head content before it is presented in the body tags

Having trouble with my meteor site, thought it was Google indexing, now suspecting an issue with the Spiderable package. Meteor version 1.1.0.3 is in use, along with spiderable package and gadicohen:phantomjs as suggested by meteorpedia. The current issu ...

What is the solution to the problem "How can you resolve the issue where 'Cannot set property 'ref' of undefined' occurs"?

My goal is quite simple - I just want to retrieve data from Cloud Firestore. Below is the code snippet I am using: import React from 'react'; import firebase from "react-native-firebase"; export default class newsFeed extends React.Component { ...

Employing v-btn for navigating to a different route depending on whether a specific condition is satisfied

Is there a way to prevent this button from redirecting to the specified URL? I want to implement a validation check in my method, and if it fails, I need to stop this button from performing any action. Any suggestions or assistance would be highly apprec ...

Modify vanilla JavaScript carousel for compatibility with Internet Explorer

I am currently in the process of creating a website that incorporates a carousel similar to the one found at the following link: https://codepen.io/queflojera/pen/RwwLbEY?editors=1010 At the moment, the carousel functions smoothly on opera, chrome, edge ...

How is it possible for a function to accept a char array as a char pointer and have the ability to modify the value of an element within the array?

When I declared a char pointer as a parameter of a function and passed a char array as an argument, I was informed that char pointer and char array are distinct types. Despite this, the function was able to accept a char array as a char pointer. Furtherm ...

What is the difference between using array pointers and vectors in C++?

Similar Query: Exploring the performance gap between arrays and std::vectors in C++ I am curious to determine which option is faster and consumes fewer resources. I tend to believe that vectors are more dependable and secure, while pointers to arrays ...

Is there a way to make Outlook show only the caption of a link instead of the entire URL?

In my PDF file, I have set up a button for sending an email. The email is a request that needs approval or denial. I want the recipient to respond with just 2 clicks: Click on either "Approve" or "Deny" (a new email will pop up) Click on "send" - and it& ...

Learning to interpret various data types from a file

I am working with a text file that contains a combination of strings, integers, and floating-point numbers. Here is an example of the format: Asher 10 14.5 Julia 14 15.5 My task is to parse this data into three separate arrays. Since C does not have a ...

Show a message on form submission rather than redirecting

I'm working on a simple sign-up form and I want to show a success message directly on the page instead of redirecting to another page after submission. Is it better to display the message as a pop-up, an alert, or just on the page itself? <form a ...

What is the best way to address cookie issues while working on a full stack application that utilizes Vue and Express.js?

Developing a full stack application requires me to use Vue on port 5173 and Express on port 3000. One issue I face is the inability to store credentials in the frontend for backend communication during development. This challenge can be addressed by servin ...

"Add elements to the beginning of an array using PHP

When using the PHP code below, the values are displayed. However, since I do not have control over the API output, I am interested in prepending the data with additional output like {"id":0,"name":"Begin","description":"this is my description","url":"http: ...