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:

https://i.sstatic.net/91uqg.png

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

In Typescript, you can easily group a string into sections that consist of digits like 345-67, along with text containing a

I have a string that looks like this: "[111-11] text here with digits 111, [222-22-22]; 333-33 text here" and I am trying to parse it so that I can extract the code [111-11], [222-22-22], [333-33] along with their respective text descriptions. The challeng ...

Leveraging the source of an image from asset variables

Lately, I've been experiencing issues with displaying images on my page, specifically when trying to show a list of images. The problem arises when attempting to store the image URL in a variable or object instead of hardcoding it directly into the s ...

Populate select2 with the selected value from select1 without the need to refresh the page or click a button

Being a novice in PHP and Javascript, I am looking for a way to populate the "info" select dropdown based on the selected value from the "peoplesnames" dropdown without refreshing the page or using a button. Here's my code: HTML: <select id="peo ...

Enhancing Website Performance with Vue.js 2.0 Lazy Loading

I'm attempting to implement Lazy Loading for my components in Vue.js 2.0 (within a Laravel 5.3 project). As per the guidelines, I should proceed like this: Vue.use(VueRouter); const Forum = resolve => require(['./Components/Forum/Forum.vue& ...

IE throwing an invalid argument error when making an AJAX request

I have a strange issue with my ajax request - it works perfectly fine in all browsers except for IE, specifically IE10! The error message I am encountering in the IE console is as follows: SCRIPT7002: XMLHttpRequest: Network Error 0x80070057, Invalid arg ...

Error: The function react__WEBPACK_IMPORTED_MODULE_6___default.a.useState is not defined as a function

Hey there! I have been working on some ReactJS code using material-ui, but it seems like I made a mistake with the placement of function handleClickOpen() and function handleClose(). Unfortunately, now my code doesn't compile. Can you help me fix it? ...

Tips on enhancing an array by separating values with vertical bars instead of commas

I am trying to store checked values in an array and separate them with vertical bars instead of commas. Is there a way to achieve this using the jQuery map .get() function? Any suggestions or links you can provide would be greatly appreciated. Thank you in ...

Continuing to use a function multiple times may lead to a type error as it is not a

My program is designed to be a quiz where users have to answer questions. After answering, they will see a summary and then get the option to submit or redo the questions. The issue arises when users choose to redo a question. Upon redoing it, the summary ...

Invoker of middleware and stack functions for Express.js with a focus on capturing the response object

It appears that the expressjs app contains a stack of Layer object Arrays. What function is utilized to pass the I am curious about: When a request is sent from the http client, which function is called first and how are the stack array functions with mi ...

Is it possible to utilize an API response within a conditional statement in NextJS?

I am working on a change password feature that interacts with an API for verification. If the current password entered is incorrect, I want to display an error message. If you have any suggestions on how to proceed or if there are any flaws in my approach ...

Transform a <td> into a table-row (<tr>) nested within a parent <tr> inside an umbrella structure

Similar questions have been asked in the past, but I still haven't found a solution to my specific inquiry. Here it is: I have a table that needs to be sortable using a JavaScript plugin like ListJS. The key requirement is that I must have only one & ...

What is the process for including a new item in an array of objects?

const data = [ { title: 'Tasks', items: ['complete assignments', 'study for exams'], }, { title: 'Ongoing', items: ['learn new skills', 'work on projects'], }, { titl ...

What is the best way to combine two sections in html/css/bootstrap?

I've been trying to create a simple webpage with a navigation bar and a section below it, but I keep running into an issue where there's unwanted white space between the nav bar and the next section in blue. Is there a way to eliminate this gap a ...

Arrange records in ascending order by phone number when multiple are returned on the same date

Currently, I am working on an Angular application that is designed to keep track of tuxedo rentals. The main feature of the app is a table that displays information from an array stored in the controller. The initial task I completed was listing the items ...

Dynamic fade effect with GSAP on scroll

Currently, I am attempting to implement a fade out animation with GSAP Scroll Trigger. The aim is for the page to first scroll across the X axis of the title before scrolling up and fading out. While I have made some progress, I am facing an issue where th ...

watchWebpack is compiling all the files

As per the webpack documentation on watching files webpack can keep an eye on files and recompile them whenever there are changes. My understanding is that this implies webpack will only compile the files that have been modified. I have a configuratio ...

The TypeORM connection named "default" could not be located during the creation of the connection in a Jest globalSetup environment

I've encountered a similar issue as the one discussed in #5164 and also in this thread. Here is a sample of working test code: // AccountResolver.test.ts describe('Account entity', () => { it('add account', async () => { ...

Troubleshooting Problems with Cookie and Session Management

I'm encountering an issue while trying to set cookies and session values during login on the backend, which is built in node js. However, when react calls the API to verify these cookies or session values, they are returning as undefined... My middle ...

Using javascript, add text to the beginning of a form before it is submitted

I'm trying to modify a form so that "https://" is added to the beginning of the input when it's submitted, without actually showing it in the text box. Here's the script I have so far: <script> function formSubmit(){ var x ...

How is it possible for this variable to be altered without any modifications made to it in the current function?

This particular function receives two arrays as input: arrOne, which is an array comprising arrays of numbers, and arrTwo, which is an array containing numbers. My goal here is to generate every possible combination, followed by obtaining the unique combin ...