Using conditional statements in a forEach iteration

Looking to Apply a Unique Function to a Specific Object in an Array

In my current project, I have set up a forEach loop to iterate through various records from a database. Each record generates a 'panel' on the interface.

Preview of the panels:

https://i.sstatic.net/JpNA4.png

The issue arises when dealing with a landscape photo for the first panel, causing alignment problems with the rest due to its larger width requirement. To address this, I need to implement an exception within the loop to handle this unique case.

Here's the code snippet:

fetch(
"https://(apiurl)/" ) //sending a GET request to the database
.then(handleError) //switches to .catch if error occurs
.then((data) => {
  data.records.forEach((record) => {
    let galleryitem = document.createElement("li");
    galleryitem.setAttribute("class", "splide__slide is-visible");
    galleryitem.setAttribute("aria-hidden", "false");
    galleryitem.setAttribute("tabindex", "0");
    galleryitem.setAttribute("style", "margin-right: 28px; width: 25vw");
    listing.appendChild(galleryitem);
    let gallerycontent = document.createElement("div");
    gallerycontent.setAttribute("class", "slider-square");
    galleryitem.appendChild(gallerycontent);
    let imgwrapper = document.createElement("div");
    imgwrapper.setAttribute("class", "slider-square_img");
    gallerycontent.appendChild(imgwrapper);
    let de_img = document.createElement("img");
    de_img.setAttribute("class", "slider-square_photo");
    de_img.setAttribute("src", record.fields.ArtLink);
    de_img.setAttribute("loading", "lazy");
    de_img.setAttribute("sizes", "(max-width: 479px) 84vw, (max-width: 991px) 48vw, 36vw");
    imgwrapper.appendChild(de_img);
    let textcontent = document.createElement("div");
    textcontent.setAttribute("class", "text-opacity");
    gallerycontent.appendChild(textcontent);
    let art_title = document.createElement("h3");
    art_title.setAttribute("class", "slider_title");
    art_title.textContent = record.fields.Title;
    textcontent.appendChild(art_title);
    let art_desc = document.createElement("h3");
    art_desc.setAttribute("class", "slider_descriptor");
    art_desc.textContent = record.fields.Descriptor;
    textcontent.appendChild(art_desc);
  });
})
.catch(function writeError(err) {
  //captures and logs errors
})

My attempts at including a conditional statement within the loop to adjust the width uniquely for the first image have been unsuccessful. An example would be:

if (data.records.record == [0]) { galleryitem.setAttribute("style", "margin-right: 28px; width: 50vw"); }

However, this approach doesn't produce the desired outcome. Any suggestions?

(Also, noteworthy is that I'm utilizing the splidejs library for the slider functionality)

EDIT: Inclusive of the complete code for clarity, along with a captured section from the array table >> https://i.sstatic.net/r6AzN.png

Answer №1

All you need to do is simply determine the index of the current item in the loop.

data.records.forEach((record, index) => {
    const galleryitem = document.createElement("li");
    galleryitem.setAttribute("aria-hidden", "false");
    galleryitem.setAttribute("tabindex", "0");
    galleryitem.style.cssText = `margin-right: 28px; width: ${index === 0 ? 50 : 25}vw`;
});

Make sure to also attach the galleryitem to a container within the loop itself.

Answer №2

An alternative approach is available: for better readability, consider using Template literals

fetch( 'https://(apiurl)/' ) // initiate a GET request to the database
.then( handleError )        // moves to .catch if an error occurs
.then( data =>
  {
  let LI_attr =
    { className     : 'splide__slide is-visible'
    , 'aria-hidden' : 'false'
    , tabindex      : '0'
    , style         : 'margin-right: 28px; width: 50vw' 
    }  
  data.records.forEach( (record, indx)  =>
    {
    listing.appendChild( 
      Object.assign( 
        document.createElement('li')
        , LI_attr
    ) )
    .innerHTML = `
      <div class="slider-square">
        <div class="slider-square_img">
          <img class="slider-square_photo"
              src="${record.fields.ArtLink}"
              loading="lazy"
              sizes="(max-width: 479px) 84vw, (max-width: 991px) 48vw, 36vw" >
        </div>
        <div class="text-opacity">
          <h3 class="slider_title">${record.fields.Title}</h3>
          <h3 class="lider_descriptor">${record.fields.Descriptor}</h3>
        </div>
      </div>`;
      
    if (indx===0)
      LI_attr.style = 'margin-right: 28px; width: 25vw'  // adjust width for subsequent records

    });
  })
.catch(function writeError(err) {
  // catches and logs any errors that occur
})

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

Transferring a large volume of JSON objects to a database using API post requests

Currently, I'm faced with the challenge of sending a large amount of JSON objects to a database through API post calls. However, upon attempting to send all these objects individually, I encounter numerous HTTP errors, predominantly 400 errors. My in ...

Using three.js to manipulate the camera's movement on the geometry generated in Autodesk Viewer from Point A to Point B

I am currently working on transitioning my camera view state from Point A to Point B within the Autodesk viewer. To achieve this, I am creating a path using LineDashedMaterial and have successfully displayed the line connecting Point A and B. Below is the ...

Unable to adjust custom link menu font size

I have designed a unique custom menu called SANDUSKY with the css classes of no-hover. It is positioned alongside HOME, ABOUT, GALLERY, STORE, CONTACT which serve as the navigation menus. While attempting to customize SANDUSKY, I successfully altered the c ...

Strange occurrences observed on array mapping post-state alteration

Greetings to all during these challenging times! Currently, I am delving into Firebase and ReactJS and have encountered a peculiar issue involving state updates in React and the array map functionality in JavaScript. Below is the code snippet showcasing my ...

An unusual outcome occurred while attempting to duplicate the text

After copying the letter A, I noticed that an empty string is being logged to the console instead of the expected A. However, when I paste, the console does successfully log the letter A. document.addEventListener('copy', handler); document ...

Animating overlapping div elements using jQuery

I am currently using jQuery's animate() function to adjust the size of a "row", but I am facing an issue with a badge that sometimes appears on the row. The problem is that the badge gets hidden during the animation, which doesn't look good. I ha ...

The system cannot locate the module: Unable to find '@reactchartjs/react-chart-2.js'

I've been working on implementing this chart using the npm module called react-chartjs-2. I followed these steps to install the module: Ran the command: npm install --save react-chartjs-2 chart.js As a result, my package.json file now looks like th ...

What is the best way to combine and merge JSON objects that consist of multiple sub-objects?

I am working with a JSON response that contains multiple objects consisting of two main objects - datacenter and environment: "deployments": [ { "datacenter": { "title": "euw1", ...

What is the best method to restore a table cell to its original width?

Here's a quick overview of the issue I'm facing: http://jsfiddle.net/k2Pqw/4/ Once I adjust the red td width, I'm struggling to revert it back to its original size. Setting it at 25% doesn't dynamically adjust like the other tds, it r ...

What causes the axios Library to fail in initiating a request if the API call does not begin with "https://"?

This issue has been resolved, but I still want to ask it in order to gain a better understanding of the underlying processes. So, I am using an API to retrieve data on the current weather in a specific city. The API call (as per the provider's documen ...

Incorporate dynamic JavaScript content within an HTML document

Currently, I am facing an issue with a webpage that I need to load in order to extract some information. Using HttpClient and Jsoup worked well for loading the majority of the content on the page. However, my problem lies with certain elements that are onl ...

Insert a parameter or substitute the existing value if detected

Trying to create a JavaScript regex that searches for a parameter in a URL and replaces its value if found. If the parameter is not found, it should be added to the URL. Here are a couple of scenarios: http://www.domain.com/?paramZ=123456 https://www.dom ...

Using the Context API dispatch (consumer) within the _app.js class component in Next.js

How can I access the dispatch Context API methods in the _app.js file? The issue I am facing is that I am using React hooks along with Context API, and as _app.js is a Class component, I cannot directly use hooks within it. Below is my current code snipp ...

Determining Asynchrony in Node.js Through Programming

Is there a way to assess if a function can be executed asynchronously without requiring a callback? I am currently working with Node.js on the Intel Edison platform and utilizing mraa. The native C++ functions like i2c.readReg(address) do not have provisi ...

What is the proper way to employ if and else if statements within Angular2?

Here's a question that has been duplicated on my How to utilize *ngIf else in Angular? post! ...

dividing a circle in half with CSS using an image background

Is it possible to divide a circle into 2 parts using both RGB and URL images? Here is an example of how I want it to look: https://i.sstatic.net/r5sWj.png I have managed to write code that works with RGB, but I am unsure how to achieve the same effect w ...

Display secret content upon hovering with a stylish animation

My current structure is as follows: HTML: <ul> <li> <span>asd</span> adsafsadlvjnsd </li> </ul> CSS: span { width: 0; } li:hover span { width: 60px; } In this setup, the content inside the span tag is h ...

"Exploring the process of transferring an ID from one service to another using the select feature in Angular

I need to store the ID I receive from one service into another using the select element. Here is my approach: <select class="form-control" id="select_fac" [(ngModel)]="rep.idfac"> <option selected disa ...

What is the best way to retrieve an array of strings from JSON using PHP and display them in a table format

I'm dealing with a JSON structure that looks like this: { "id": 30, "output": { "status": "ok", "data": { "text/plain": "Array({\"a\":\"orange\",\"b\":\"fruit\"},{\"a\":&bsol ...

What is the best way to use a JavaScript function as a callback?

I'm struggling with understanding callbacks, especially how they function. Here is my function: function checkDuplicateIndex(values, callback) { $.ajax({ type: "POST", url: url, data: "command=checkIndexAlbumTracks& ...