skip to Main Content

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 fristnamen")
    let nazwisko = window.prompt("give lastnamen")
    let userObject = {};
    let userInput = prompt("Please enter some data");
    userObject.data = userInput;

}

2

Answers


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

    I hope this might help you.

    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search