ignore current index in for loop

I am currently facing an issue with an if statement inside a for loop.

The scenario involves retrieving a list of files from the directory filesSAS, iterating through each one, and converting them from csv to JSON. After conversion, I check if the output contains an id in its object. If it does, I copy the file using the

copyFile(dirSas, dirOut, filename)
function. If an id is present, I add a date and save the file as CSV.

The problem arises during the first iteration where the file is copied, but the saveCSV function is also executed, which overrides the desired result. My goal is to copy the file if the id is absent during this iteration and proceed to the next iteration. I have attempted to place the saveCSV function inside the for loop with no success.

EDIT: In cases where the for loop encounters an object without an id, the file should be copied. If an id is present, I aim to append a date and save the file as CSV.

let noId = [{
user:"Mark",
job:"Job"
}]

let withId = [{
id:1,
user:"Mark",
job:"Job"

}]

output
 let withId = [{
    id:1,
    user:"Mark",
    job:"Job"
    date: 12-09-2019
    }]


const saveNewFile = async (filesSAS, dirSas, dirOut, dirArchive) => {
  filesSAS.forEach(async filename => {
    const newData = await csv().fromFile(`${dirSas.path}/${filename}`);
    for await (const iterator of object) {
      if (iterator.Id === null || iterator.Id === undefined) {
        await copyFile(dirSas, dirOut, filename);
      }
      rec.Date = moment(Date.now()).format("DD-MMM-YYYY");
    }

    await saveCSV(newData, `${dirOut.path}/${filename}`, "output");
  });
};

Best regards

Answer №1

One interesting feature of JavaScript is the continue statement, which allows you to skip over a single iteration of a loop. You can learn more about this by visiting the following link: JavaScript Break and Continue

Dealing with asynchronous loops can present challenges when trying to restart them in a sequential manner. In such cases, using an if statement to skip the remaining iterations may be a suitable alternative.

Answer №2

To achieve the desired outcome, you can use a boolean flag that gets updated when an id is not found.

const saveNewFile = async (filesSAS, dirSas, dirOut, dirArchive) => {
  filesSAS.forEach(async (filename, index) => {
    const newData = await csv().fromFile(`${dirSas.path}/${filename}`);
    for await (const iterator of object) {
      if (iterator.Id === null || iterator.Id === undefined) {
        await copyFile(dirSas, dirOut, filename);
      }
      else {
          rec.Date = moment(Date.now()).format("DD-MMM-YYYY");
          await saveCSV(newData, `${dirOut.path}/${filename}`, "output");
      }
    }
  });
};

Answer №3

Well, I managed to achieve it by refactoring my code.

const saveNewFile = async (filesSAS, dirSas, dirOut, dirArchive) => {
  filesSAS.forEach(async filename => {
    const newData = await csv().fromFile(`${dirSas.path}/${filename}`);
    if (!newData[0].hasOwnProperty(pkCol)) {
      copyFile(dirSas, dirOut, filename);
    } else {
      for await (const rec of newData) {
        rec.DateCreated = moment(Date.now()).format("DD-MMM-YYYY");
      }
      await saveCSV(newData, `${dirOut.path}/${filename}`, "output");
    }
  });
};

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

Unable to retrieve data-id from <td> on click event

Can someone help with an issue I'm having in my code? Here is the snippet where I create a table data element: html += "<td data-id='test' class='journal' style='max-width:200px;'>"+record.source_account_code+"& ...

What is the best way to link my PHP with MySQL in order to execute an AJAX query?

I am currently working on making this page sortable using a dropdown selection menu. At the moment, there are only two different car makes displayed and they are not sorting properly. My ultimate goal is to enable sorting by make, model, and year, but I ne ...

Obtaining objects from a Meteor collection on the server triggers a "Must have Fiber to proceed" error

As a beginner in creating meteor apps, I am working on a project that involves querying git issues from a specific repository. The goal is to generate tasks from these issues after retrieving them using the Github API. However, I keep encountering an error ...

Encountering a CORS header issue while working with the Authorization header

Here is the code snippet I am currently working with: https://i.stack.imgur.com/DYnny.png Removing the Authorization header from the headers results in a successful request and response. However, including the Authorization header leads to an error. http ...

Searching by element within a JSON array

I've tried various solutions from different sources but haven't been able to find the correct answer yet. create table mstore ( muuid uuid PRIMARY KEY, msid text, m_json JSONb[] not NULL ); Inserted the first row: insert into mstore (muuid, msid ...

unable to display loading image prior to upload

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html lang="en"> <head> <title>Unique Prints</title> <meta charset="utf-8"> <meta name="viewport" conte ...

Adding an active class to a selected list item can easily be accomplished by targeting the

Hey there, I'm attempting to apply a class to the selected list item and also add a class when scrolling to a specific div. For instance, if I scroll to div#six, the number six (6) in the menu should also have the 'active' class. [Check out ...

What's the best way to incorporate mouseenter() and mouseleave() into several elements sharing the same class?

I have a vision for a fun game where players must navigate from one platform to another without falling off the edges. The game starts when you hover over the initial platform, and success is achieved by reaching the final platform. However, failure occurs ...

"Encountering issues when trying to retrieve a global variable in TypeScript

Currently facing an issue with my code. I declared the markers variable inside a class to make it global and accessible throughout the class. However, I am able to access markers inside initMap but encountering difficulties accessing it within the function ...

What is the method to retrieve response text?

This is the content of my register.js file: var formdata = new FormData(); formdata.append("name", name.value); formdata.append("username", username.value); formdata.append("email", email.value); formdata.append("password", password.value) ...

Transmit the bound data (using ng-model) to a custom AngularJS directive

/*I am looking to define the maxDate as vmEndDate*/ app.directive('myDatepicker', function ($parse) { return function (scope, element, attrs, controller) { var ngModel = $parse(attrs.ngModel); alert(element.va ...

Quick question about utilizing Ajax with spans

<span name = "menu"> <!-- javascript here --> <!-- content loaded via ajax --> </span> <span name = "content"> <!-- content loaded via ajax --> <!-- updated by buttons from the menu--> </span> Seeking a ...

Exploring the retrieved data from the AJAX/ASP.NET controller update for a fresh perspective

When selectbox is called, it triggers the 'getDepAndMan()' function. A value is extracted from the selectbox (successful). The function calls methods in the 'GetDepartmentAndManager' controller (successful). The controller returns ...

One array comprises of all elements found in a separate array

After grappling with this problem for a while, I still haven't been able to find a solution. If I have 2 arrays structured like this: array1 = [ { name: 'John', age : 25}, { name: 'Jane', age : 58} ] array2 = [ { name: ...

Children divs unable to access Angular scope

This section is from my controller: mbpMod.controller("bookController", function($scope,api) { ... $scope.bookTable=new BookTable(); $scope.bookLabel="Book"; ... } On the HTML page, it functions properly with this code: <md-tab> ...

Exploring nested objects in Javascript through iterating and extracting all properties in a continuous loop (Updated)

In my code, I created an object with two sub-objects structured like this: var testObject = { "page":{ "type": "ePurchase", "title":"Purchase confirmation" }, "user": { "name": ...

Is there a way to showcase the output of the <div id="height"> on the height of the rectangle?

My Current Project Currently, I am in the process of developing a picture framing calculator using a combination of HTML, CSS, and JavaScript. Functionality of the Calculator For this calculator, users will input values such as: Frame Width (wf): 16 ...

Load Vue 3 components dynamically using a string-based approach

Exploring ways to dynamically load components based on a string input. Here is an attempt at achieving this: <component v-for="component in components" :is="eval(component)" /> However, this approach does not yield the desired r ...

What is the best way to update the style following the mapping of an array with JavaScript?

I want to update the color of the element "tr.amount" to green if it is greater than 0. Although I attempted to implement this feature using the code below, I encountered an error: Uncaught TypeError: Cannot set properties of undefined (setting 'colo ...

Accept only requests from my Chrome extension

I have successfully set up a NodeJS server with Express on DigitalOcean. My Chrome extension is able to make GET calls to the server without any issues. However, I am looking to enhance the security of the middleware below: // Add headers app.use(function ...