What is the best way to verify an array of objects within an asynchronous function?

I am struggling with validating an array of objects being sent to the server. It seems that my current code is not working properly when the array is empty or if the objects within it are invalid. I'm confused about why it's not functioning as expected.

Here is the code snippet I am using:

 const ingredientValidator = ingredients.some(({ingredient, quantity})=>{
        ingredient.trim().length == 0 || quantity.trim().length == 0
      }) 

  if(ingredientValidator){
     return res.status(409).send({
       message: 'fully point ingredients'
     })  
  }

What could be causing this issue?

P.S An example of an array of objects:

[  
   {  
      ingredient:'foo',
      quantity:'bar'
   },
   {  
      ingredient:'foo',
      quantity:'bar'
   },
   {  
      ingredient:'foo',
      quantity:'bar'
   }
]

Can you provide guidance on how to solve this problem?

Answer №1

To solve the issue, all you have to do is adjust the return statement in ingredientValidator:

const ingredientValidator = ingredients.some(({ingredient, quantity})=>{
  return ingredient.trim().length == 0 || quantity.trim().length == 0
});

// or

const ingredientValidator = ingredients.some(({ingredient, quantity})=>
  ingredient.trim().length == 0 || quantity.trim().length == 0
);

If you include curly braces after the arrow function, it behaves like a regular function block that requires a return statement to output anything. Alternatively, removing the curly braces should result in an implicit return.

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

Display endless data within a set window size

I am looking to create a fixed-size window for displaying text from the component <Message/>. If the text is longer, I want it to be scrollable within the fixed window size. See screenshot below: Screenshot export default function AllMessages(){ ...

jQuery - patience is required until all elements have completely faded away

I am facing a unique challenge: I need to trigger an action after two specific elements have been faded out simultaneously. The code snippet for this task is as follows: $("#publish-left, #publish-right, #print-run").fadeOut(function(){ //do something ...

Can you share a method in javascript that extracts href= and title values, similar to PHP's preg_match_all() function?

I received an HTML string as :var code; I am looking to retrieve all the values of href and title similar to how it is done using PHP's preg_match_all(). I have achieved a similar task in PHP with the provided example but now I am curious about how I ...

Why isn't this working? I'm attempting to trigger a sound when I hover with my cursor, but it only plays when I click instead

When I click on it, it works fine. But I can't seem to get it to work on hover. Can someone help me out? This is the HTML code: <body> <audio autoplay id="HAT2" > <source src="OOOOO_1_HAT.mp3" > Your browser doesn't support t ...

Bug in toFixed causing incorrect results

function calculateTaxAndTotalRent(rent) { var phoneCharges = parseFloat($('#phone_charges').val()); phoneCharges = phoneCharges.toFixed(2); rent = parseFloat(rent); rent = rent.toFixed(2); var tax = parseFloat((rent * 15) / 1 ...

Differences between React class properties and ES6 class properties

With React 16.2, defining class properties is done differently with the tagLine example shown below: class Header extends React.Component { tagLine = "Super Hero"; render() { .... } } Contrastingly, in ES6 classes, it's not possible to define ...

Leveraging underscore.js for null verification

let name = "someName"; if(name !== null) { // perform some action } Currently, I am utilizing http://underscorejs.org/#isNull. How can I achieve the same functionality using underscore.js? Is there any noticeable performance enhance ...

Harnessing the power of Express to tally user records within subdocuments

My index route for users involves counting the records they have in the subdocument. Here is my current implementation: router.get('/', middleware.isLoggedIn, (req, res, next) => { // Retrieve all users from the database User .find({} ...

Manually reloading the page causes issues with AngularJS routing functionality

I've been attempting to manually reload the page from my browser, but unfortunately it's not working and is displaying an error message: Cannot GET /rate/4 This is what my route setup looks like in Angular: angular.module('routing&ap ...

Make the navigation bar stay at the top of the page when scrolling past another element with a top position of 100vh

Trying to explain a unique concept here. I want a nav bar fixed in the position of top:100vh, so that as I scroll down and reach the next section, the navbar sticks at the top rather than staying stuck at the beginning with position:fixed top:0. The aim is ...

Attempting to retrieve exclusively the checked records in Vue.js

Currently, I am referring to this library for checkboxes. As I delve into the code, I notice how it is declared and utilized. Initially within the el-table, we have @selection-change="handleSelectionChange". They have initialized an empty array ...

Focus on selecting just one button within Angular

By retrieving values from a database and displaying them using ng-repeat within a div: <div ng-controller = "myTest"> <div ng-repeat="name in names"> <h4>{{name.name}}</h4> <button ng-class="{'active ...

Custom Log4j rollover script to automatically delete logs once the filesystem usage exceeds a specific threshold

Utilizing log4j for logging in my application has been beneficial. I am now exploring the option to automatically delete compressed files when the filesystem reaches 80 percent usage. While log4j lacks a built-in appender for this task, it does offer the S ...

Sending properties in NextJS from the server side (Application routing)

In order to share data for each request, I have created an object with this data in the rootLayout. export interface IProps { children: React.ReactNode; data: any; } export default function RootLayout(props: IProps) { const {children} = props; ...

What is the best way to access nested objects in React Native?

Here is the JSON data I am working with: [ { id: 51, name: 'Boat Neck Blouse', image: { id: 669, date_created: '2018-08-27T10:05:39', date_created_gmt: '2018-08-27T10:05:39', date_modified ...

Issue with Electron: parent window not being recognized in dialog.showMessageBox() causing modal functionality to fail

Struggling with the basics of Electron, I can't seem to make a dialog box modal no matter what technique I try. Every attempt I make ends in failure - either the dialog box isn't modal, or it's totally empty (...and still not modal). const ...

Mongoose failing to persist subdocument

After trying to insert into my collection, I noticed that the sub-document is not being saved along with it. This issue has left me puzzled. This is the scheme/model I am working with: import { Schema, Document, Model, model } from 'mongoose' ...

Next.js is like Gatsby but with the power of GraphQL

I'm curious if it's possible to set up GraphQL in Next.js similar to how it's done in Gatsby, allowing me to query pages and retrieve data from them. Are there any plugins available for Next.js that work like Gatsby-file-source and gatsby-ma ...

Utilize Redux in conjunction with TypeScript to seamlessly incorporate a logout feature

My login page redirects to a private /panel page upon successful login with an accessToken. I am utilizing the Redux store to verify the token in the privateRoute component. Challenges I'm encountering: I aim to enable logout functionality from t ...

Tips for executing forEach on a promise?

I am currently working with a function that returns a promise of an array: async function functionReturningPromiseOfUserIDs(): Promise<string[]> My question is, can I use the forEach method on the array returned by this function? async function runF ...