how to add object created from user input into array of objects javascript

53 Views Asked by At

I can't understand how to make an object which will be make from user input and then added to array of objects

Here is what i tired:

let Contact = {
    fristname: "fname",
    lastname: "lname",
}

const Contacts = []

function addContact(fristname, lastname){
    let imie = window.prompt("give fristname\n")
    let nazwisko = window.prompt("give lastname\n")
    let userObject = {};
    let userInput = prompt("Please enter some data");
    userObject.data = userInput;

}
2

There are 2 best solutions below

0
Code Venus On
    const Contacts = []

    function addContact(fristname, lastname){
        let userObject = {};
        userObject['firstname'] = window.prompt("give fristname\n");
        userObject['lastname'] = window.prompt("give lastname\n");
        userObject['data'] = prompt("Please enter some data");
        Contacts.push(userObject);
        console.log(Contacts);
    }

I hope this might help you.

2
Nina Scholz On

You need a loop for collecting data with exit and a function for adding the data into contacts.

The convention in Javascript is to use variables who starts with a small letter. An uppercase letter indicates a incanciable function/class and all caps indicates a constant value.

This approach takes short hand properties for the object, where variables are taken as properties with same name.

For checking loop it utilises the optional chaining operator ?., because prompt could return null which is not a string for taking an upper case value.

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

const contacts = [];

let loop;

do {
    addContact(
        prompt("give firstname"),
        prompt("give lastname"),
        prompt("Please enter some data")
    );
    loop = prompt('Another Contact? [Y/N]', 'N');
    if (loop?.toUpperCase() === 'N') loop = false;
} while (loop)

console.log(contacts);