Executing a For Loop in Java Script while integrating it with SNS message notifications

Java Script is still quite new to me and I could really use some assistance with a specific issue in the code snippet below. I am using an IF Statement to validate an incoming SNS Message. If it matches, I want to display the message values.

  else if (obj.intent === "list" && obj.message === 'success'){

            var innerHTMLval = '<table class="test"><tr><td class="test-loc"><img src="favicon.png" width="10%"></td><td class="test-loc"> View</td></tr>'
                + ' <tr><td class="forecast">'+ obj.artikel0+ '</td><td class="forecast">' + obj.stueckzahl0 + '</td> </tr>'
                + ' <tr><td class="forecast">'+ obj.artikel1+ '</td><td class="forecast">' + obj.stueckzahl1 + '</td> </tr>'
                + ' <tr><td class="forecast">'+ obj.artikel2+ '</td><td class="forecast">' + obj.stueckzahl2 + '</td> </tr>'
                + '</table>'            
                document.getElementById('display').innerHTML = innerHTMLval;            
 }

While everything is working smoothly, I am now curious if there is a way for me to utilize a for loop to dynamically add lines based on the payload count.

This is how my payload looks:

{
    "intent": "list",
    "message": "success",
    "artikel0": "A",
    "stueckzahl0": 10,
    "artikel1": "B",
    "stueckzahl1": 10,
    "artikel2": "A",
    "stueckzahl2": 10,
    "artikel3": "C",
    "stueckzahl3": 10,

}

Can anyone advise me on how to add these lines using a For loop that adjusts according to the number of lines in the payload?

Thank you so much

Answer №1

To set up a body variable and add to it in the following way:

var bodyContent = "";
 for(property in object){
   if((property.indexOf("article") != -1) || (property.indexOf("quantity") != -1)){
     var endingTag = (property.indexOf("quantity") != -1) ? '</td></tr>' :  '</td> ';
     var startingTag =  (property.indexOf("quantity") != -1) ? ' <td class="forecast">' :  ' <tr><td class="forecast">';
     bodyContent += start + obj[property] +  endingTag;
   }
 }
var innerHTMLvalue = '<table class="test"><tr><td class="test-loc"><img src="favicon.png" width="10%"></td><td class="test-loc"> View</td></tr>'  
+ bodyContent +'</table>'

Answer №2

var data = {
    "intent": "list",
    "message": "success",
    "item0": "A",
    "quantity0": 10,
    "material0": "mat10",
    "item1": "B",
    "quantity1": 11,
    "material1": "mat11",
    "item2": "A",
    "quantity2": 10,
    "material2": "mat10",
    "item3": "C",
    "quantity3": 10,
    "material3": "mat10",

}

var content = "";
 for(key in data){
   if((key.indexOf("item") != -1) || (key.indexOf("quantity") != -1) || (key.indexOf("material") != -1)){
     var isItem = (key.indexOf("item") != -1);
     var isMaterial = (key.indexOf("material") != -1);

     var endTag = (isMaterial) ? '</td></tr>\r\n' :  '</td>';
     var startTag =  (isItem) ? '<tr><td class="forecast">' :  ' <td class="forecast">';
     content += startTag + data[key] + endTag;
   }
 }
var display = '<table class="test"><tr><td class="test-loc"><img src="favicon.png" width="10%"></td><td class="test-loc"> View</td></tr>'  
+ content +'</table>'

output from content

/*

<tr><td class="forecast">A</td> <td class="forecast">10</td> <td class="forecast">mat10</td></tr>
<tr><td class="forecast">B</td> <td class="forecast">11</td> <td class="forecast">mat11</td></tr>
<tr><td class="forecast">A</td> <td class="forecast">10</td> <td class="forecast">mat10</td></tr>
<tr><td class="forecast">C</td> <td class="forecast">10</td> <td class="forecast">mat10</td></tr>

*/

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

JavaScript functioning exclusively for specific list items within an unordered list

After implementing JavaScript on my website, I noticed that it only works when clicking on certain list items (li's) and not on others. Specifically, the functionalities for Specialties, Contact Us, and Referral Schemes are not working correctly. ...

Tips for controlling the upload of a .exe.png file or converting a .exe file to a png file for uploading in angular 8

I had originally set up restrictions to only allow image file types such as JPG, JPEG, PNG, and TIFF. However, I discovered that users were able to upload .exe files simply by renaming them. For example, changing dell.exe.png or dell.exe to dell.png allo ...

Experiencing difficulties while attempting to organize an array?

// const first = data.groups_with_selected[7]; // const second = data.groups_with_selected[20]; // data.groups_with_selected.splice(2, 0, first, second); // data.groups_with_selected.splice(9, 1) // data.groups_with_selected ...

PHP successfully sent a JSON response, however, the $.getJSON method did not receive it

I'm encountering an issue with the JSON response that my PHP code is producing. This is the PHP code on the backend: case 'deleteMySale': $id = $_GET['product_id']; $dataNoSer = "Are you sure you want to delete the sale ...

What function does an API fulfill within the MVC architecture?

My quest to fully grasp MVC continues. I understand that in a traditional setup, the controller processes user requests for a webpage. For example, if a user wants to see 5 blogposts, the controller instructs the Model to fetch those posts from the databa ...

Learn how to create a validation function for phone numbers in a React application that keeps the button disabled until a valid phone number

import React,{useState} from "react"; export default function ValidatePhone() { const [phoneNumber, setPhoneNumber] = useState(""); const [disableButton, setDisableButton] = useState(true); function handleChange(e) { setPho ...

What is the best way to incorporate Vue.component with modules or Vue CLI?

I'm having trouble figuring out the correct way to declare a Vue.component within export default. This issue arises from following a tutorial on vuejs.org. https://i.sstatic.net/PH3VN.png Instead of using var app = new Vue, I am implementing it as ...

What is the best way to include JSON in an SNS message using AWS CLI?

What is the proper way to send an exact JSON structure using aws cli in the command line (without using a file)? aws sns publish --topic-arn "arn:aws:sns:us-east-1:12345:myproject_serverlessscheduler_sns" --message '{"key1":"value1", "key2":"value2"} ...

Learn the step-by-step process of sending an email through the SendGrid API V3 utilizing templates with a comprehensive example

Currently, I am delving into the SendGrid documentation regarding templates and stumbled upon this: You have three options to send transactional templates: Utilizing the SMTP Relay Including the template ID in the templates parameter of the W ...

Ways to obtain the output of an If/Else statement

It seems like I might be missing something, but I am unsure of how to extract the result from an else-if statement. Take this code snippet that I've been working on for example: In this scenario, the output would read "It's warm!", and what I wa ...

Guidelines for adjusting canvas dimensions based on parent div attributes

Trying to insert a p5.js canvas into a div using the divs width to control the canvas width, within a jekyll post. The markdown file includes a div positioned at the top of the post. <div id="myCanvas"</div> <script src="/js/p5Sketches/firstP ...

Using Django forms within a modal: dynamically redirecting and managing errors

My current project involves integrating a login form within a modal window using Django. I found a helpful guide at this link which has been working effectively so far. However, I am now aiming to enhance the user experience by redirecting them to their pe ...

Unable to transfer an array from getStaticProps method in Next.js

Whenever I pass a JSON array from getStaticProps in Next.js, I encounter this specific error message when trying to access it. TypeError: Cannot read property 'contentBody' of undefined module.exports../pages/[author]/[article].js.__webpack_expo ...

JavaScript function that fetches data from local storage and displays it in an HTML table

I've been exploring how to incorporate a bootstrap datatable into my project. Rather than using pre-set data, I want to allow users to input their own data through a form and store it in localStorage. Understanding that I need to stringify and parse ...

What are your thoughts on combining a JSON object with HTML?

When using ASP.NET MVC, it is possible to return a JSONResult. return JSON(new { View = RenderViewAsString("MyView", model), wasSuccessful = true}) This approach combines HTML and data in a single JSON object. The goal is to utilize strongly typed HtmlHe ...

Is there a more efficient method for handling this JSON dataset?

After delving into Sitepoint's "Novice to Ninja" and starting to explore jQuery, I can't help but question if there is a more efficient way to write the code I've put together. The resounding answer appears to be "yes." All these cumbersome ...

Ignoring Database Without Using Hashes

I am currently troubleshooting why this script is returning "login faileda" and terminating. I understand the technical reason (no match, but there should be a match). Initially, I suspected it was an issue with the password hash, but I removed that for te ...

Issue with menu display after clicking icon

On my website, I am trying to set up an icon that will display a menu bar for mobile users. I have written some JavaScript code for this functionality, but it's not working as expected. My approach involved creating an element called "Menu" and assign ...

Tips for establishing conditional guidelines and mandatory fields within Vue?

Struggling to implement conditional required fields on a form. The approach I've taken is by setting a data field notRequired: false, and then using it in the fields like this: :required="!notRequired". This allows me to make certain fields not requir ...

Updating Array State in ReactJS: Best Practices

I have been working on implementing a tag feature using React, but I am facing challenges with updating the tags dynamically. Regarding TagsInput.js import React, { useState } from "react"; import CancelIcon from "@material-ui/icons/Cancel& ...