Determine if the object's value is present

My current JavaScript setup looks like this:

var NAMES = []; 
function INFO(id,first,middle,last){ 
  var newMap = {};
  newMap[id] = [first, middle, last];
  return newMap ;   
}

Next, I have the following code block:

for (var j = 0; j < NUMBER.length; j++) {   //let's say there are three values
    var my_name = all_names[j]; // which contains "185, 185, 185"              
    if (NAMES[my_name] !== 185){ //This is where I need to perform a check              
        NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));                      
    }else{

    }               
}
alert(JSON.stringify(NAMES , null, 4));

Below is a screenshot of the alert displayed:

I used the number "185" for demonstration purposes. What I'm trying to achieve is checking if the id of 185 already exists, and if it does, proceed to the else block. I've attempted using typeof, undefined, etc., but haven't been successful. (In essence, I should only have one instance of "185").

Any suggestions or advice on how to accomplish this? Thank you!

Answer №1

From what I gather, it seems like you need to loop through NAMES and inspect each element. One approach could be utilizing the javascript function [].some:

if (!NAMES.some(function(item){return item[my_name]})) {
    ...
} else {

}

Answer №2

To avoid duplicate entries, you can utilize the NAMES object instead of an array like so:

var all_names = [185, 185, 181], 
    NAMES = {};
for (var j = 0; j < all_names.length; j++) {   //assuming there are three values
    var my_name = all_names[j]; // contains "185, 185, 185"  
    NAMES[my_name] = ["sean","sdfsd","sdfsfd"];
}

alert(JSON.stringify(NAMES, null, 4));

Answer №3

To begin with, I suggest creating a JS Fiddle or CodePen to showcase the code in action.

The issue lies in the usage of NAMES[my_name]. Since NAMES is an array, calling NAMES[my_name] retrieves the entire object created in the INFO function, rather than checking if the object has an attribute matching the value from the my_names array.

While not the most elegant solution, here is a snippet that demonstrates what you actually want to achieve:

var NAMES = []; 
function INFO(id,first,middle,last){ 
  var newMap = {};
  newMap[id] = [first, middle, last];
  return newMap ;   
}

all_names = ["185", "186", "185"]

for (var j = 0; j < all_names.length; j++) {
    var my_name = all_names[j]; 
    if (NAMES.length == 0) {
        NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));                      
    } else {
        var match = false;
        for (var x = 0; x < NAMES.length; x++) {
            console.log(NAMES[x][my_name] + ' : ' + my_name);
            if(NAMES[x][my_name]) {
                match = true;
            } 
        }
        if (!match) {
            NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));
        }
    }
}
alert(JSON.stringify(NAMES , null, 4));

Note the condition checking NAMES[x][my_name] - it verifies if the item at array index 'x' possesses an attribute of 'my_name' (e.g. "185"). This likely aligns with your intended functionality. While there are more concise ways to handle this task in JavaScript, the provided code should clarify the fundamental issue at hand.

Answer №4

You can try implementing this code snippet using the hasOwnProperty method :

for (var j = 0; j < NUMBER.length; j++) {
    var my_name = all_names[j];   
    if (!NAMES[my_name].hasOwnProperty("185")){              
        NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));                      
    }else{

    }               
}

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

When the user clicks on an element, my JavaScript code dynamically updates the CSS property by changing the window

When a tag is clicked in HTML triggering an onclick event, the CSS property that was updated in the JavaScript does not persist. The changes appear momentarily and then disappear once the window is refreshed. Javascript: <script type="text/javascript"& ...

What is the process of integrating data from the OpenWeatherMap API into the WindowInfo feature of Google Maps?

My current project involves retrieving weather information from the openweathermap API and displaying it in an infowindow on Google Maps. However, there seems to be an issue where I am getting data from the previous marker instead of the current one. var ...

Tips for looping through every item that has a specific class name

I have tried various methods and researched numerous ways to achieve this, but I am struggling to implement it in my code. My goal is to iterate through each <li> element and check if the text inside the <span class="state"> tag is ei ...

Issue with integrating the jquery tokeniput plugin in asp.net mvc 3

Having trouble integrating the jQuery Tokeninput plugin into my MVC application. Something seems off with the setup... The Code I'm Using: <input type="text" id="MajorsIds" name="MajorsIds" /> <script type="text/jav ...

When attempting to display an identical image on two distinct canvas elements in Angular 6

I am facing an issue where the image is only rendered on the second canvas instead of both canvases. I need assistance in finding a solution to render the same image on both canvases. Below is a screenshot demonstrating that the image is currently only re ...

Why should <template> be used in Vuetify?

Exploring the possibilities of Vuetify 2.0 in my current project has led me to dive into the v-stepper component, designed for displaying progress through numbered steps. In the example provided in the playground, I noticed the use of the <template> ...

Local variable reference getting lost in a loop during a jQuery Ajax call

Currently, I am facing an issue with my jQuery ajax calls within a loop. The problem arises when each ajax call returns and I need to retrieve a specific value associated with the original call. However, due to further iterations in the loop, the value of ...

Phone Validation for Contact Form 7

Recently, I was tasked with creating a landing page for a job interview. The challenge was to include validation on the phone number field so that it has to be between 9 and 10 numbers in length, along with another validation requiring the phone number t ...

Having trouble setting up node-gyp on ubuntu

npm http 200 https://registry.npmjs.org/weak/-/weak-0.2.2.tgz npm http GET https://registry.npmjs.org/bindings npm http 304 https://registry.npmjs.org/bindings > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8dfcdc9c3e898 ...

The standard TextField functionality was disrupted by the update to MUI v5

After typing a comment in the TextField and trying to click Done, nothing happens because the TextField still has focus. The first click removes the focus, while a second click is needed to complete the action. <TextField id={'generalCom ...

Eliminate any unnecessary tags located before the text

I am facing a challenge with the following code snippet. The Variable contains a string that includes HTML tags such as <img>, <a>, or <br>. My goal is to eliminate the <img> tag, <a> tag, or <br> tag if they appear befo ...

The React client is unable to establish a connection with the server socket

Recently diving into the world of socket-io and react, utilizing express for the backend. The socket.io-client version being used is 3.0.3, while the backend's socket-io package matches at 3.0.3 as well. Interestingly enough, the server handles connec ...

Dynamic CSS Changes in AngularJS Animations

I am currently working on a multi-stage web form using AngularJS. You can see an example of this form in action by visiting the link below: http://codepen.io/kwakwak/full/kvEig When clicking the "Next" button, the form slides to the right smoothly. Howev ...

Sharing and displaying images on Sails JS platform

Using Sails JS, I am attempting to upload an image and display it in a view. Queries: The uploaded image is located in .tmp/uploads, how can I retrieve it from a view? Is there a method to access the uploaded image? The image's name is altered in ...

What is the best way to pass a JSON object from R to Plumber in a format that JavaScript can interpret as an array instead of

My goal is to receive a JSON raw response from R Plumber and then utilize it in Angular. However, I am encountering an issue where the JavaScript Framework is interpreting it as a string instead of recognizing it as JSON format. "[{\"id&bsol ...

What is the best method to extract the values of objects in an array that share

var data= [{tharea: "Rare Disease", value: 3405220}, {tharea: "Rare Disease", value: 1108620}, {tharea: "Rare Disease", value: 9964980}, {tharea: "Rare Disease", value: 3881360}, ...

Sending a CSS class name to a component using Next.js

I am currently in the process of transitioning from a plain ReactJS project to NextJS and I have a question. One aspect that is confusing me is how to effectively utilize CSS within NextJS. The issue I am facing involves a Button component that receives ...

What is the best way to ensure that the state is updated only when the user begins typing in a text

I am currently working on a text editor-related code and my main focus is to update the state of the editor only when the user starts typing in the editor. The state should be updated under the following scenarios: 1. Update the state when the user begin ...

Capture all Fetch Api AJAX requests

Is there a way to intercept all AJAX requests using the Fetch API? In the past, we were able to do this with XMLHttpRequest by implementing code similar to the following: (function() { var origOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.p ...

The component in React does not refresh after updating the state

I have a React page where I am displaying a list of quizzes fetched from an external API. There's also a "New Quiz" button that opens a dialog with a form for users to create a new quiz. My issue is with making the table re-render once the POST reque ...