Using Javascript to create alerts that display all objects

Is there a way to send a single alert with all objects? Whenever I attempt it, I keep getting undefined or [object, object]

var array  =[];


function object ( name, username, password)
this.name = name
this.user = username
this.pwd  = password

var object1 = new object ("jack","jacky","123") 
var object2 = new object ("bob", "bobby", "qwe")

array.push(object1);
array.push(object2);

alert () //How can I achieve this??

Answer №1

var array = [];

function createObject(name, username, password) {
  return {
    name: name,
    user: username,
    pwd: password,
  }
}

var obj1 = createObject("alice", "alice123", "abc") 
var obj2 = createObject("dave", "davey", "pass123")

array.push(obj1, obj2);

and then you can choose between:

var resultMessage = 'array'.concat(':', ' ', JSON.stringify(array, null, 2))
alert(resultMessage) 

/*
array: [
  {
    "name": "alice",
    "user": "alice123",
    "pwd": "abc",
  },
  {
    "name": "dave",
    "user": "davey",
    "pwd": "pass123",
  }
]
*/

or this...

array.forEach((arrItem) => {
  var message = 'object'.concat(':', ' ', JSON.stringify(arrItem, null, 2))
  alert(message)
})

/*
object:   {
  "name": "alice",
  "user": "alice123",
  "pwd": "abc",
}
*/
/*
object: {
  "name": "dave",
  "user": "davey",
  "pwd": "pass123",
}
*/

or even this one...

var msg = array.reduce((_message, arrItem) => {
  var objectMsg = 'object'.concat(':', ' ', JSON.stringfiy(arrItem, null, 2), '\n')
  _message = _message.concat(objectMsg)
  return _message
}, ''}
alert(msg)

/*
object:   {
  "name": "alice",
  "user": "alice123",
  "pwd": "abc",
}
object: {
  "name": "dave",
  "user": "davey",
  "pwd": "pass123",
}
*/

Answer №2

If you're looking to create a loop with the items in an array, you can follow this approach:

var array  =[];


function object ( name, username, password) {
  this.name = name
  this.user = username
  this.pwd  = password
}

var object1 = new object ("jack","jacky","123") 
var object2 = new object ("bob", "bobby", "qwe")

array.push(object1);
array.push(object2);

array.forEach(function (item) {
  alert("name: " + item.name + ", user: " + item.user + ", pwd: " + item.pwd);
});


Alternatively, if you prefer to display all values in one message, you can try this method:

var array  =[];


function object ( name, username, password) {
  this.name = name
  this.user = username
  this.pwd  = password
}

var object1 = new object ("jack","jacky","123") 
var object2 = new object ("bob", "bobby", "qwe")

array.push(object1);
array.push(object2);

var message = "";

array.forEach(function (item, index) {
  message += "object" + (index + 1) + ": name: " + item.name 
          + ", user: " + item.user + ", pwd: " + item.pwd + "\n";
});

alert(message);

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

Allocating memory for a single element within an array

There is a challenge in determining the size of an array during runtime due to dependencies. Therefore, memory allocation needs to be done for each element similar to how it's done in linked-lists. Is there a way to achieve this with integer arrays? ...

"Utilizing Bootstrap's hamburger menu for a sleek solution when your menu becomes overcrowded

One interesting aspect of Bootstrap is its ability to collapse menu items into a hamburger menu within the navbar at specific window size breakpoints. However, there are instances where even on larger screens that exceed these breakpoints, the hamburger bu ...

SEO Optimized pagination for pages without modifying the URL

On my website, I utilize pagination to navigate to various event pages. However, search engines are not picking up the conferences on these pages. Take a look at the code snippet below... <a href="javascript:;" class="first" title="First" onclick="getC ...

Various web browsers are displaying distinct jQuery errors when executing the code

I'm currently working on validating and uploading images using multiple accept inputs with the help of jQuery, AJAX, and PHP. I have successfully added a validation function that is working correctly, but the form is not submitting. Additionally, Chro ...

Guide on utilizing the "window" attribute within Angular framework

Recently, I came across a neat "Scroll back to top" button that caught my eye: https://www.w3schools.com/howto/howto_js_scroll_to_top.asp Despite being new to Angular, I wanted to give it a try and implement this feature myself. However, every attempt I ...

Invalid Blob URL functionality on Android web browsers

I have developed a straightforward web application using .NET (including Entity Framework) and AngularJS for fetching PDF files. Everything works smoothly on desktop browsers and iOS browsers, but I am encountering difficulties in getting it to function pr ...

It seems that in Laravel 5.3, it's challenging to add a script to a view for an autocomplete

Currently, I am working with Laravel 5.3 for my internship. However, I have encountered a frustrating issue that I need help with: I am trying to implement an "autocomplete" field on a page, but it doesn't seem to be functioning correctly. The error ...

Modify JSON date format to a shorter version using the first 2 letters of the month and the year

Looking to convert date values in a JSON array from "December 2016" format to "D16". Hoping to accomplish this using Regex, any assistance would be greatly appreciated. [["November 2016","December 2016","January 2017","February 2017","March 2017"],["tot ...

What is the method for turning off client-side validation for a specific field with jQuery when a checkbox is selected?

This is the HTML code used in my MVC Razor page. <form> <input id="inputLPR" asp-for="LicensePlateNo" class="form-control"/> <input type="checkbox" id="isEnableBypass"><label for=&qu ...

How to Use Ember.js with MongoDB for Querying Data Using "AND"

I've been making great progress on my Emberjs application, but I've hit a roadblock that's leaving me stumped. Despite scouring the web for answers, I can't seem to find a solution. The issue at hand involves a dropdown feature in my a ...

I am interested in generating a unique set of numbers, grouping them into an array, and then converting the array into a string

How can I store the digits of a random number into an array and then convert it to a string while keeping the digits hidden from the user? I attempted to implement this but encountered issues with only storing two numbers. What adjustments can I make to ...

Changing a div's properties is causing jQuery to behave strangely

Something strange happened while coding in javascript, especially with some jquery functions. Check out my code below <?php // Encoded in UTF-8 if(isset($_SESSION['username'])) { ?> <script type="text/javascript"> funct ...

Converting CSV data into JSON format using NodeJs and integrating it with MongoDB

Here is how my CSV file is structured: "Some Comment here" <Blank Cell> Header1 Header2 Header3 Value1 Value2 Header4 Value3 Value4 I am looking to convert this into JSON format and store it in MongoDB as follows: Obj: { Key1: Header ...

Navigating a series of options

I am currently working on improving my programming skills. My goal is to implement a feature where I can cycle through an array of objects, displaying each object in a text label. Here's how far I've gotten: Starting with the object at index 0, ...

Update the text on the form submit button after it has been submitted

Is there a way to change the text on a submit button after it has been clicked? I have a form with a button and I want to switch the text from "click" to "Next" once the form has been submitted. <form> <div class="form-grou ...

Incorporating React Native elements into a native Android interface (UI element)

I am facing an issue in my react-native application where I have a native Android view (created in java) rendering correctly. However, when I attempt to include one of my react-native javascript components within it, I encounter this error: java.lang.Cla ...

I am having trouble getting two similar Javascript codes to function simultaneously

Using a common JavaScript code, I am able to display a div when a certain value is selected. http://jsfiddle.net/FvMYz/ $(function() { $('#craft').change(function(){ $('.colors').hide(); $('#' + $(this ...

A single click causes the entire row of cards to extend seamlessly

The cards on this tab were generated using a loop and the data is sourced from a database. When I click on the "Show More" button, the entire visible column expands along with it. The expansion does not reveal the content immediately; instead, the content ...

Iterating through arrays to gather information

When I call an API to retrieve a list of Jobs, the output is structured as follows: SimpleXMLElement {#357 ▼ +"Jobs": SimpleXMLElement {#368 ▼ +"Job": array:13 [▼ 0 => SimpleXMLElement {#371 ▼ +"ID": "J000006" +"Name ...

Retrieving dynamically generated form components upon submission in a React application

I am facing an issue with a modal containing a dynamically rendered form in my React component. I want to gather all the user-entered field values and send them to the backend. Below is the code for rendering the dynamic form fields: import React from &ap ...