javascript tutorial on how to insert user-generated objects into an array of objects

I'm struggling to figure out how to create an object that will be made from user input and then added to an array of objects.

Here is what I've attempted:

let NewContact = {
    firstName: "first name",
    lastName: "last name",
}

const ContactList = []

function addNewContact(firstName, lastName){
    let first = window.prompt("Enter first name\n")
    let last = window.prompt("Enter last name\n")
    let userData = {};
    let userInputData = prompt("Please enter some data");
    userData.data = userInputData;

}

Answer №1

To efficiently gather data and add it to a collection, you'll need a loop with an exit condition and a function specifically designed for updating the contacts list.

In Javascript, it's customary to name variables starting with a lowercase letter. Uppercase letters typically signify constructible functions or classes, while all caps are usually reserved for constant values.

This method leverages short hand properties in objects, where variables automatically become object properties with identical names.

When validating the loop, it uses the optional chaining operator ?.. This is necessary because prompt may return null, which cannot be converted to uppercase for comparison purposes.

function addContact(firstname, lastname, data) {
    contacts.push({ firstname, lastname, data });
}

const contacts = [];

let loop;

do {
    addContact(
        prompt("Enter first name"),
        prompt("Enter last name"),
        prompt("Please provide some data")
    );
    loop = prompt('Add another contact? [Y/N]', 'N');
    if (loop?.toUpperCase() === 'N') loop = false;
} while (loop)

console.log(contacts);

Answer №2


const Contacts = []

function addNewContact(firstname, lastname){
    let newUserObject = {};
    newUserObject['firstname'] = window.prompt("Please enter first name");
    newUserObject['lastname'] = window.prompt("What is your last name?");
    newUserObject['data'] = prompt("Share some information with us");
    Contacts.push(newUserObject);
    console.log(Contacts);
}

Hopefully this function will be useful for you.

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

Encountering a data property error while trying to render ejs using axios

I am encountering an error message "TypeError: Cannot read property 'data' of undefined" when trying to display results.ejs using data from an API. Can someone help me identify what's incorrect with the rendering code? Thank you. index.js: ...

PHP divided using looping logic

Greetings, folks! I present to you a perplexing puzzle that is designed to put your mental prowess to the test. Let's first take a look at the enigmatic array in question: Array ( [0] => Array ( [id] => 1, [p] => 150, [w] => 120, ) ...

awaitMessages feature does not capture slash commands

In my development process, I have a file named botReady.js that is designed to run as soon as the bot becomes ready. In this file, there is a specific section dedicated to handling a bump bot in a designated channel obtained using the client.channels.fetch ...

Experience the power of live, real-time data-binding for date-time input with AngularFire in 3 different

Here is a simplified version of my code snippet: tr(ng-repeat='entry in ds3.entries | orderBy:orderByField:reverseSort | filter:query as results') td input.screen(type='datetime-local', ng-model='entry.date_recei ...

The JSON.stringify() function helps to convert data into a JSON-formatted string, avoiding any potential "c

connection.query( 'SELECT DeskName FROM desks WHERE stat = ?',["Booked"], function(err, rows){ if(err) { throw err; }else{ try{ var dataToParse = new Array(); dataToParse = rows; res.render('workspaces.html',{parsedArray : JS ...

AJAX (Vanilla JavaScript): Sending Image through HTTP Request

I am a beginner with ajax and prefer not to use frameworks. I attempted to use PHP to determine if a file is set and display either true or false, but it didn't work as expected. I'm unsure of where I went wrong. Below is my HTML and JS code: & ...

I am working with a multidimensional array that contains subarrays, and I need to extract and print only the "id" element from the main index in a PHP JSON format. I am trying

Example of an Array Structure. This code snippet displays a multi-dimensional array containing series ID and related data. Array ( [0] => Array ( [series_id] => 42 [userid] => 1 ...

HTML: Determine the Precise Location of a Div Element That is Centered

Imagine I have this image: Is there a way for me to determine the x/y or left/top properties of my canvas if it is centered using the following CSS: #canvas-container { width: 100px; height:100px; margin: 0px auto; } Note ...

Validating Email Addresses using jQuery

Currently, I am utilizing jQuery to validate whether a user has input a valid email address into my text box. The objective is to have the submit button disabled by default and only enable it once a valid email address has been entered. However, if the use ...

Ways to transfer information from a function within one element to another element

I have two components: one that logs the indexes of a carousel and I need to pass these indexes into the second component. First Component <template> <div class="container container--white"> <Header /> <carousel-3d @a ...

Unable to write or upload error in a Node Express application

My GET and POST APIs are functioning properly, however, my app.put is not working as expected. https://i.sstatic.net/Oc0QT.png Upon sending a PUT request to localhost:3001/contacts/1 using Postman, I am unable to see the console.log output: https://i.ss ...

Bidirectional data binding in Vue.js enables seamless communication between parent and child components, allowing for dynamic

Trying to implement v-for and v-model for two-way data binding in input forms. Looking to generate child components dynamically, but the parent's data object is not updating as expected. Here's how my template is structured: <div class="cont ...

Having trouble with getting v-cloak to function properly when dealing with asynchronous requests

I wanted to explore using the v-cloak directive to showcase a loading spinner while certain data properties in vue js are being loaded asynchronously for me to integrate into a table component. After successfully applying and styling my v-cloak styles on ...

Experimenting with the inner workings of a method by utilizing vue-test-utils alongside Jest

Is there a way to properly test the internal logic of this method? For instance: async method () { this.isLoading = true; await this.GET_OFFERS(); this.isLoading = false; this.router.push("/somewhere"); } This method toggles isLoading, ...

Iterate over an array containing numerous objects using a jQuery each loop

In my JavaScript array, there are multiple objects as shown below: var myArray = [{ year:'2015', model:'BMW', used:false, extras: [{buckets:'no',sportWheels:'yes'},{buckets:'no',sportWheels ...

What could be causing the submenus in my intricate menu component to lose focus when input is entered?

I'm currently working on developing a menu using the MUI Menu component. The goal is to have a popup input control (such as Autocomplete, TextField, Select, or a custom form) appear when a menu item is clicked, based on the choice made from the menu. ...

Updating View in Angular 2 ngClass Issue

I'm encountering some challenges with updating my view using ngClass despite the back end updating correctly. Below is my controller: @Component({ selector: 'show-hide-table', template: ' <table> <thead> ...

Categorize elements in an array based on a specific keyword

Struggling with my AngularJS (1) application, I can't seem to figure out how to split an array of items into separate arrays grouped by item. In simpler terms, I have an array with different items and I want to group them by their uuid like this: [ ...

The progress bar for Ng-file-upload does not function properly when used in conjunction with offline

Using ng-file-upload for file uploading in my home has been successful, as I am able to upload files without any issues. However, I encountered a problem where the progress bar only appears when offlinejs is disabled in the index.html file. It seems that ...

What is the best method for calculating income and expenses within a JavaScript expense tracker?

I'm facing an issue where I can't add the value of a checked radio button to an object in a different function. Even though there are no errors, nothing gets added. My project involves creating an expense tracker, and adding either income or exp ...