Storing multiple data records into a javascript object?

In my program, I have to prompt the user to enter customer information. The information includes first name

, last name

, phone number

and grocery items

(separates each array point).

The request will ask the user for information until the user clicks the "Cancel" button or accepts nothing. eg:

peter,pho,123-324-2333, beans,carots,cereal
karen,smite,122-333-1223, milk,pudding

      

Every time the user enters input, I need to create an object to hold the information, and each object needs a grocery item property. So I guess it goes something like this.

cust = prompt("enter customer info");
while(cust != null){
    var array1 = cust.split(',');
    var customer = {
       custinfo:array1.slice(0,3),
       items:array1.slice(3,array1.length)
    } 
    cust = prompt("enter");
}

      

This works for the first client, but how can I store many records, I don't know how many clients the user will be entering. I tried to create an array of objects if that makes sense, for example customer[]

, but it didn't work. I split them into arrays for later use in my homework. Also how do I make a launch request until the user accepts nothing?

+3


source to share


1 answer


If you want an ordered list of items, use Array . You can combine this with a loop for

. Here's an example

function ask_questions(questions) {
    var answers = [],
        i,
        ans;
    for (i = 0; i < questions.length; ++i) { // for infinite loop, `while (true) {`
        ans = prompt(questions[i] || 'enter'); // default question
        if (!ans) break; // cancel or blank ends questioning
        answers[i] = ans; // do what you want with the data given
    }
    return answers;
}

      

The function ask_questions

takes an Array (say arr

) and the prompts

user arr.length

times, then returns the results prompt

as another array

var qs = ['enter customer info', null, 'enter2']; // null will cause message "enter"
qs.length = 4; // undefined will cause message "enter"

ask_questions(qs); // ["foo", "bar", "baz", "fizz"]

      




However, is this really the best data structure for you? You can do better with an object that has useful property names rather than indexes, and ask them to provide specific details such as their name and address, rather than leave it to them. If you leave everything up to them, you can complete your animal life story, their favorite color, etc. Or even nothing at all.

Finally, prompt

not good UX, use <input>

or <textarea>

in your final version

0


source







All Articles