Determining the presence of a value in a nested JavaScript object when the key is

The code below is used to construct an object array:

var users = {};

var user = {};
user[socket.id] = data.username;

if(users[data.roomname]){

   // Room already exists - check if user already exists 

   // if data.username does not exist in users then:

   users[data.roomname].push(user);
}
else{

   // New room

   users[data.roomname] = [user];
}

After a few iterations, the array looks like this:

console.log ( 'Users: ', users );

users  { RoomABC:
   [ { YidwzgUHPHEGkQIPAAAD: 'Mr Chipps' },
     { 'JG-gtBMyPm0C1Hi1AAAF': 'Mr T' },
     { '2JFGMEdPbgjTgLGVAAAH': 'Mr Chipps' }, ] }

The main issue is ensuring that each username is unique, so Mr Chipps should not be added again if that name already exists.

Most solutions assume the keys are known. I have attempted several methods including some, indexOf but have not been successful in simply checking if UserX already exists.

The following block of code is my latest attempt to only add the user if it is not already present in the object array. While it works, it seems rather cumbersome with nested loops and counters:

if(users[data.roomname]){

  // Room already exists - check if user already exists 
                
  let found = 0;

  // Nested loop - although functional, it feels inelegant

  Object.keys(users[data.roomname]).forEach(key => {

     Object.keys(users[data.roomname][key]).forEach(key2 => {

         if ( users[data.roomname][key][key2] === data.username ) {
            found++;
         }
     });
  });

  if ( found == 0 ) {
     users[data.roomname].push(user);
  }
}

I am still searching for a cleaner one-liner solution for this existence check, but haven't found one yet.

Answer №1

Instead of relying on keys, consider evaluating the values and terminating the process if a name is detected

if (users[data.roomname]) {
    if (!Object.values(users[data.roomname]).some(value => Object.values(value).some(name => name === data.username))) {
        users[data.roomname].push(user);
    }
}

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

Obtaining an array of 8 u64 elements from a u8 array of length 32 using Rust

Can someone provide a code snippet and possibly an explanation? I have a hash function that I use in two different programming languages, and I need to compare the results in Rust. The first usage of the hash function returns a vector of 8 u64 numbers: [3 ...

How to refresh a page in React when the browser's back button is pressed

In my React project using Material-UI, I have created a simple search form. On page A, users can input values in text boxes and select options from drop-down lists and checkboxes. The results are then displayed on page B. My issue arises when returning to ...

Adjust the size of the div to fit its content while maintaining the transition animation

I am aiming for the DIV height to automatically adjust to the text within it, while also maintaining a minimum height. However, when the user hovers their mouse over the DIV, I want the height to change smoothly without losing the transition effect. When ...

Invoking a service within the controller of the $stateprovider

I currently have my service being executed in my AppCtrl function, although this approach is not ideal. The service should only be needed when the user navigates to page2. How can I trigger my service specifically when the page2 state is active? I attemp ...

Ways to Determine if the Content in the CKEditor has Been Altered

Is there a way to detect changes in the content of CKEditor? I want to trigger a JavaScript function every time the content is updated. ...

Command in Selenium Webdriver for initiating a mouse click

Currently, I am in the process of writing tests for a Java application that has been created with the Vaadin framework. To conduct these tests, I have opted to utilize the Robot Framework. In certain instances, I must implement robot framework commands suc ...

Building a dynamic tab menu using JavaScript: A step-by-step guide

In order to generate dynamic tab menus with JavaScript, I am seeking a solution that does not rely on jQuery as it may not be supported by all mobile devices. Any advice for replicating the same functionality using pure JavaScript would be greatly apprec ...

How can timestamps be set in MongoDB during an insertOne() operation without relying on new Date() as in PostgreSQL's NOW()?

timestamp: { $currentDate: { $type: "timestamp" } } }); The insert() method is not functioning properly Is there anyone who can assist me with this issue? ...

What is the best way to implement a fadeout or timeout for success and warning alerts in OpenCart 2.2?

Is there a way to set a timeout for alert boxes in Opencart 2.2 so that they disappear after a few seconds? I've tried the code below, but it didn't work out. Alternatively, is it possible to make the popup disappear when clicking anywhere on the ...

Two values are returned from the Node.js Mongoose Exports function

Currently, I am encountering an issue with my project where a service I developed is up and running. However, it is not providing the desired value as a response. Specifically, the goal is to generate coffee items linked to specific companies. Whenever new ...

Enforcing character limits in summernote

Is there a way to set a character limit on Summernote? I've tried setting maxlength on the textarea without success. Check out the Summernote GitHub page $("#textareaid").summernote({ toolbar:[ ['style', ['style']], ...

What are the steps to resolve the error 'content-type missing boundary' and encountering the issue with getBoundary not being recognized as a function?

fetchCarouselData: async (params) => { let bodyFormData = new FormData(); for (let prop in params) { bodyFormData.append(prop, params[prop]); } return axios({ method: "post", url: `${baseURL}/fetchCarouselData`, data: b ...

Error: The specified module '/node_modules/.vite/vue.js?v=31b05063' does not export the required 'default' element

I am struggling to find a solution to this problem in my vue3.js project. The console is showing an error related to the import statement in pinia store. I attempted changing the first line of the import to "import Vue from 'vue';" (without curly ...

Variations in how words are organized within a sentence

Can you help me devise an algorithm to identify all possible combinations of word groupings in a sentence without changing the order of the words? For example, for the sentence "the test case phrase," the various combinations would include: ['the te ...

The art of posting with ExpressJS

I'm encountering a problem where the data submitted through a form to my POST route is not getting passed on to a database document, even though the redirection works fine. I'm unsure of how to troubleshoot this issue. blogpost-create.ejs &l ...

Manually sending the form via Ajax for submission

I'm facing an issue where I am trying to utilize ajax to call a servlet upon form submission. However, the ajax call is not being triggered and the page ends up reloading. To solve this problem, I have set up a manual trigger for the form submission, ...

Utilizing a dropdown selection value to filter a list in JavaScript

I have an array of objects where I need to filter based on a dropdown selection. const itemsList=[{ "id":"123", "problems":{ "causes":[ { "SSEnabled": true, "IndusEnabled": false, "LogEnabled": true } ] } ...

Sending BCrypt hash to a different function

I am having trouble encrypting a password using BCrypt and passing it to another function to store it in the database. An error message saying "ReferenceError: hashedPass is not defined" keeps appearing on write-to-db.js:18 The code below encrypts the pas ...

Perform a series of observables from a dynamically generated array

Currently, I am in the midst of a project (Angular2) where I am dynamically creating Observables and storing them in an array. var ObservableArray : Observable<any>[] = []; //populating the Observable array dynamically for (var i = 0; i < this.ma ...

Guide on incorporating JavaScript code within a PDF document

Looking for guidance on implementing JavaScript in PDF files I am seeking advice from those familiar with adding JavaScript actions to PDF documents, as this is a new area of exploration for me. While I have experience with JavaScript in web development, ...