Is there a more efficient method for iterating through an object of arrays to detect errors in function arguments?

In my quest to create a function that validates the userId or channelId, I am looping through the data store provided below.

let data = {
    users: [
      {
        uId: 1,
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b70727d5b70767a727735787476">[email protected]</a>',
        password: 'kif123',
        nameFirst: 'Kifaya',
        nameLast: 'Shehadeh',
        handle: 'kifayashehadeh',
      }, 
      {
        uId: 2,
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="69101c1a291004080005470a0604">[email protected]</a>',
        password: 'yus1234',
        nameFirst: 'Yusra',
        nameLast: 'Mahomed',
        handle: 'yusramahomed',
      },
    ],
    channels: [
      { 
        channelId: 1,
        name: 'DREAM',
        ownerMembers: [1,2,3,4,5],
        allMembers: [1,2,3,4,5],
        isPublic: false,
        messages: [
          {
            messageId: 1,
            uId: 1,
            message: "Coffee is better at 12am.",
            timeSent: Math.floor((new Date()).getTime() / 1000),
          },
          {
            messageId: 2,
            uId: 2,
            message: "Chocolate is better 24/7.",
            timeSent: Math.floor((new Date()).getTime() / 1000),
          },
        ],
      },
      { 
        channelId: 2,
        name: 'COFFEE',
        ownerMembers: [1,2],
        allMembers: [1,2,3,4,5],
        isPublic: true,
        messages: [
          {
            messageId: 1,
            uId: 4,
            message: "Dark chocolate isn't even chocolate. Seriously.",
            timeSent: Math.floor((new Date()).getTime() / 1000),
          },
        ],
      },
    ],  
  };

My current approach within the function involves:

//invalid channelId
let error = true;
    for (const channel of data.channels) {
      if (channel.channelId !== channelId ) {
        error = false;
      }
    }
    //invalid user
    for (const user of data.users) {
      if (user.uId === authUserId) {
        error = false;
      }
    }

    if (error === true) {
      return {
        error : 'error'
      }
    }

This process feels rather inefficient and more akin to C than javascript. Is there an elegant one-liner that can handle this without sacrificing readability? Additionally, I'm struggling with implementing proper error checking logic. How can I immediately return an error and exit the function upon detection?

Answer №1

To simplify the process, consider mapping the users and channels to only include the properties you need - .channelId and .uid. Then, use .includes twice to verify that both values are present in their respective arrays.

const channelIds = data.channels.map(c => c.channelId);
const userIds = data.users.map(u => u.uId);
if (
  !channelIds.includes(channelId) ||
  !userIds.includes(authUserId)
) {
  return {
    error: 'error'
  };
}

Although it's possible to condense this into a single line, it may sacrifice readability. (Remember, while technically any JavaScript code can be condensed into a single line, it doesn't necessarily enhance maintainability.)

if (!data.channels.map(c => c.channelId).includes(channelId) || !data.users.map(u => u.uId).includes(authUserId)) { return { error: 'error' };}

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

Generating arrays in the output of a Talend JSON field is essential for organizing and structuring

Having trouble with the tWriteJSONField component in Talend, specifically with pushing data into a tRESTClient object that has very specific API requirements. I can extract the required data using tWriteJSONField but it's not in the correct format tha ...

Trigger a function in JavaScript/jQuery after an event has finished executing and has provided a return value

Is there a way in JavaScript/jQuery to execute a function after all callback handlers following a keyDown event have finished? I have noticed that checking the value of a form input box immediately after the keyDown event returns an empty value, but when I ...

Ways to Insert Text and Values into an Array

{{ "user": "randomuser", "message": "require assistance" }, { "user": "automated assistant", "message": "do you need any help?" }, { "user": "randomuser", "message": "another inquiry" } I am seeking to extract additional paragraphs ...

Unexpected outcomes when rigging a .dae model in Three.js with Blender

I have been working on creating a rigged model for use in a browser using Three.js. Before rigging the model, it loads perfectly fine, allowing me to move and rotate it without any issues. However, after rigging the model, the pieces load in different loca ...

Array containing two objects in a two-dimensional format

In the example provided, I am working with a 2D array. Link to the example: https://codesandbox.io/s/v0019po127 I am noticing different results depending on whether I use the browser console or Codesandbox's console. I have attempted using JSON.str ...

What is an alternative way to rewrite this regular expression without relying on the deprecated API?

My JavaScript code uses a regular expression, myRegexp, to match numbers in a string: var myRegexp = new RegExp('[0-9]+'); The code then extracts numbers from the string and returns an array: var string = '123:456'; var nums = []; wh ...

What is the best way to use jQuery to set the height of one div equal to another div

Edited: I am facing a situation with a 3-column layout - Column A, Column B, Column C. The height of Column A is dynamic and I need to set the same height for both Column B and C. For instance, Column A contains a tabbed panel with varying heights based ...

Interacting div elements with jQuery's dynamic content

I am searching for a way to populate a div with content based on my click selection. To begin, I create a dynamic table like the one below: user name total hours worked button(unique id fetched from database) user name total ho ...

Obtaining the TemplateRef from any HTML Element in Angular 2

I am in need of dynamically loading a component into an HTML element that could be located anywhere inside the app component. My approach involves utilizing the TemplateRef as a parameter for the ViewContainerRef.createEmbeddedView(templateRef) method to ...

Using an array in jade rendering

I'm currently working on a node.js server using express and I'm facing an issue with passing an array to jade rendering. Here's the code snippet from my node.js file: router.get('/render', function(req, res) { var t; var ...

Utilizing a for loop in conjunction with JSON data

Can someone help me with this issue? I can only see Jimmy Cricket's name displayed, but I want to see all the names in li tags. Any assistance would be greatly appreciated. <ul id="members"></ul> <script> var teammembers = [ {"name" ...

Choose the identical selection once more from a drop-down menu using JQuery

Below is the code containing a Select: http://jsfiddle.net/pdkg1mzo/18/ The issue I'm facing is that I need to trigger an alert every time a select option is clicked, even if the clicked option is already selected. ...

How to flip the order of elements in a Java array with specified parameters

My goal is to reverse an array, so that when I input 1 4 5 6 I expect the program to output 6 5 4 1 I have attempted to implement this functionality but keep encountering an ArrayIndexOutOfBoundsException error. import java.io.*; import java.util.*; ...

Heroku deployment failed: Push rejected due to lack of a Cedar-supported application

Trying to deploy my 3D game (created with three.js) on a Heroku server has brought up an issue. After running the command "git push heroku master," I encountered the following problem: Initializing repository, done. Counting objects: 252, done. Delta com ...

Clicking on the Jquery datepicker beforeShowDay remains possible despite all days being set as not selectable

https://i.sstatic.net/P3mII.png I've been using jQuery UI for datepicker and I'm attempting to disable certain dates. I read that this can be done using beforeShowDay when initializing the datepicker, but I'm having trouble getting it to wo ...

Create specification for the properties of the child component

I am interested in working with the props of a parent element's children and validating those props. Can I achieve this using prop-types? export default function MyComponent(props) { return ( <div> {React.Children.map(props.chil ...

Tips for iterating through a JSON object in JavaScript and building a table from it

My JSON data is structured like this: diferencias = { "1": { "1": 543.0, "0": 542.0 }, "2": { "0 1": 0.3333333333333333 } } I am trying to create a table with the outer keys as columns. This is the code I have written ...

PHP Looping Array Logic Issue

Explaining this concept is a bit tricky, especially in the title, so here it goes: I am creating a PHP Array with 12 indexes, each representing a month. These indexes will display the number of page views recorded in that specific month. To determine the ...

The novice image slideshow script in JavaScript is causing all images to disappear and generating errors

Trying to create a simple image slider that pulls information from various sources. CSS and HTML are set up properly, but adding the JavaScript logic causes all images to disappear. The console displays an error saying "Uncaught TypeError: Cannot read prop ...

When attempting to send data to the ServiceStack RESTful service, an error message of 'Access is denied' was received

I created a RESTful service using ServiceStack to send data to a database. It worked perfectly when tested locally. However, after deploying it to a server and running the same jQuery $.ajax call code, I encountered an 'Access is denied' error. I ...