Identifying the presence of a property value within a collection of objects

I am trying to verify the existence of a 'member' object with a specific 'ID' in the 'members' array of an 'EntityGroup' container object. I'm having trouble understanding why the EntityGroup.idExists(id) method is not functioning as expected:

EntityGroup = function() {
    this.members = []; // intended to store 'Entity' objects
    this.classType = null; // specifies the class type of entities it holds
};
EntityGroup.prototype = {
    addEntity: function(entityType, EntityID) {

        // TODO include .idExists() check here 
        // do not add new member if the id already exists
        this.members.push(new Entity(entityType, EntityID))

    },

    idExists: function(EntityID) {

        var idExists = false,
            member, 
            members = this.members;

        for (var i = 0; i < members.length; i++) {

            if (EntityID == members[i].EntityID) {
                idExists = true;
                break;
            } else {
                continue;
            }
        }
        return idExists;
    }
};

Entity = function(entityType, EntityID) {
    this.EntityID = EntityID;
    this.entityType = entityType;
};

g = new EntityGroup();
g.addEntity("Person", 1);
g.addEntity("Person", 2);

console.log(g.idExists(1)); // returns false, which is unexpected
console.log(g.members); 

Answer №1

Using <strong>for (x in y)</strong> loop is not suitable for looping through objects within an array because it is designed to iterate over keys of an object only.

The issue here is that the variable member is referencing the indexes of the two Entity objects instead of the objects themselves, which are at index 1 and 2. To correctly iterate through these objects, you should use the following code:

for(var i = 0; i < members.length; i++) {
    EntityID == members[i].EntityID;
}

Answer №2

The issue lies within the utilization of your for...in loop. It is crucial to use for...in solely for iterating over properties in an object, rather than items in an array.

To rectify this problem, simply substitute the existing loop with the following:

for(var i=0, len=members.length; i<len; ++i){
     var member = members[i];
     //additional code here

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

I am attempting to pass information through the body of an Axios GET request to be used in a Django backend, but when I try to print the request.body

As reported by Axios, it seems that this is a feasible solution: https://github.com/axios/axios/issues/462#issuecomment-252075124 I have the code snippet below where pos_title contains a value. export function getQuery(pos_code, id) { if (id === 94) ...

Tips for managing the three.js player mesh (md2) while incorporating cannon.js physics

Check out a cool demo I recently made the switch to using three.js (coming from a background in OpenGL and C++, so adapting to JavaScript wasn't too difficult). To get a better understanding of how to set things up, I explored various three.js exampl ...

URL resolution issue encountered with AJAX operation

My goal is to submit an HTML form to a Flask endpoint called /add_int. I'm using jQuery to intercept the form submission and send it to the endpoint using AJAX. Here's the code snippet: var form = $( this ).serialize() $.post({ ...

The issue arises when the logout component fails to render even after the user has been authenticated. This problem resembles the one discussed in the React Router

While attempting to run the react-router docs example on the browser, I encountered an issue with the AuthButton component. The problem arises when the isAuthenticated value changes to true but the signOut button fails to display. import React from ' ...

Building a dynamic webpage using AJAX, MVC, and web APIs to generate a div element filled

I'm currently working with a restful API, MVC, and ajax. My goal is to retrieve data from the backend and then display images within certain div elements. The expected outcome should resemble this example: https://i.stack.imgur.com/BFqWL.png This sni ...

Issue encountered while attempting to deactivate certain foundation CSS and JavaScript files

I am attempting to deactivate certain CSS files in the foundation framework, as they are unnecessary for my project. After installing foundation via a gem, I followed Ryan Bates' recommendation to modify the foundation_and_overrides.scss file by repl ...

Tips for correctly mapping a shuffled array in React/Next without triggering a hydration mismatch error

I've been working on a Next.js website and I'm trying to display a randomized list of famous quotes. To achieve this, I'm using lodash to shuffle the array of quotes and then mapping them onto the page. import { useMemo } from 'react&ap ...

Navigate to a New Page post Dropdown Selection

Currently working on developing a website using Github Pages where I need users to be directed to a specific page after choosing the final option. I am extracting data from a JSON file. I attempted to include an anchor tag in the JSON but it does not red ...

Ways to set a default image for an <img> tag

I am looking to set a default image to the img tag in case the user has not selected a profile picture for their account. Here is the current output: http://jsfiddle.net/LvsYc/2973/ Check out the default image here: This is the script being used: funct ...

Please proceed by submitting all radio buttons that have been checked

Seeking assistance with creating a quiz application using the MEAN stack. Once all questions are attempted, there will be a submit button for checking all selected radio buttons - option 1 corresponds to 1, option 2 to 2, and so on. The current structure o ...

Utilize Bootstrap tooltips to display live results fetched via an AJAX call

I have a bootstrap tooltip that I am trying to populate with data from an AJAX request. The text retrieved from the request should be displayed as the title property of the tooltip. Despite successfully executing the AJAX request, I am facing two issues: ...

Displaying search results seamlessly on the same page without any need for reloading

I am looking to create a search engine that displays results without the need to refresh the page. I have come across using hash as a potential solution, but I don't have much knowledge about web programming. So far, with the help of tutorials, I have ...

Ways to modify the hue of an li element in the context menu upon hovering

I'm currently working on a project that involves VueJS and Bootstrap. To enhance user experience, I've incorporated a context menu using the npm package called vue-context Vue Context Menu When a user hovers over an item on the context menu, the ...

Is there a way to preselect a vue-multiselect option when the available options are in the form of an array of objects

Is there a way to pre-select a specific value in a select drop-down created with vue-multiselect? When using a simple array of strings like this: ['Test 1', 'Test 2', 'Test 3'] It works perfectly fine. However, if I switch t ...

Attempting to establish a login system using MongoDB

I am currently working on a function to verify user login details entered in a form and compare them with data stored in MongoDB, such as email and password. However, the function seems to be malfunctioning. The expected behavior is that when a user ente ...

A step-by-step guide to loading a .php file via Ajax using JQuery when an item is selected from a dropdown

I have successfully populated a dropdown list using PHP from a database on the page named admin.php. Now, I am utilizing JQuery with Ajax functionality to display information when a surname is clicked from the dropdown menu. The goal is to call employerP ...

Editing JSON files - Substitute the $scope object with a new value

I am facing an issue with extracting data from an external JSON file for my application. Although most of the data loads into a DataTables table successfully, I am encountering problems with the $scope variable since it is referencing external data. Specif ...

"Exploring the world of digital art with JavaScript through canvas and canvas

How can I adjust the value of a canvas arc? The input accepts larger values, but not smaller ones. var btn = document.querySelector(".btn"); btn.addEventListener("click", () => { var inputVal = document.querySelector(&q ...

What is the process for modifying event (hover & click) on a legend item within highcharts?

When hovering over chart points, you can see the point value in the center of the pie chart. Similarly, when you stop hovering over a chart point, you can see the total value displayed. This behavior also applies when hovering over a legend item. const cha ...

Tips for Re-positioning the Manage Password Window in a Browser Using CSS

I am facing an issue with the Caps Lock key indication on my login page. When the Caps Lock key is on, a tooltip should be displayed below the password field. However, when the browser's "manage passwords" bubbles are shown, the tooltip gets hidden be ...