Storing multiple data entries into a javascript object? - javascript

In my program I have to prompt the user to enter customer info.
The information includes first name, last name, phone number, and grocery items (separate each array by a comma).
The prompt keeps asking user for info until user presses cancel or enters nothing.
ex:
peter,pho,123-324-2333, beans,carots,cereal
karen,smite,122-333-1223, milk,pudding
Each time the user enters input, I need to create an object to store the info, and each object needs a property grocery item. So I assume 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 customer, but how do I store many entries, I don't know how much customers the user will enter. I tried creating an array of objects, if that makes any sense , like customer[], but it didn't work.I split them into arrays for later use in my homework. Also how do I make the prompt run until user enters nothing?

If you want an ordered list of items, use an Array. You can combine this with a for loop. Here is 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 prompts the user arr.length times, then returns the results of the prompts 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 may do better with an Object which has useful property names rather than indices and ask them for specific pieces of data such as their name and address rather than leaving it up to them. If you leave it all up to them you could end up with their pet's life story and their favourite colour etc or even nothing at all.
Finally, prompt isn't a good UX, use <input> or <textarea>s in your final revision

Related

How i can get a random user from my firebase user list?

I'm developing a app and need get a random user from my firebase user list. Whenever a user registers, the system updates the user count on an especific node. So, I draw a number from 1 to the total user. And now, how do I select a user based on that number?
Assuming all of your users are stored in a /users node with keys of their uid and assuming the uid's are ordered (which they always are), there are several options.
1) Load all of the users from the /users node into an array and select the one you want via it's index. Suppose we want the 4th user:
let usersRef = self.ref.child("users")
usersRef.observeSingleEvent(of: .value, with: { snapshot in
let allUsersArray = snapshot.children.allObjects
let thisUserSnap = allUsersArray[3]
print(thisUserSnap)
})
While this works for a small amount of users, it could overwhelm the device if you have say, 10,000 users and lots of data stored in each node.
2) Create a separate node to just store the uid's. This is a significantly smaller dataset and would work the same way as 1)
uids
uid_0: true
uid_1: true
uid_2: true
uid_3: true
uid_4: true
uid_5: true
uid_6: true
uid_7: true
3) Reduce the size of your dataset further. Since you know how many users you have, split the dataset up into two sections and work with that.
using the same structure as 2)
let uidNode = self.ref.child("uids")
let index = 4 //the node we want
let totalNodeCount = 8 //the total amount of uid's
let mid = totalNodeCount / 2 //the middle node
if index <= mid { //if the node we want is in the first 1/2 of the list
print("search first section")
let q = uidNode.queryLimited(toFirst: UInt(index) )
q.observeSingleEvent(of: .value, with: { snapshot in
let array = snapshot.children.allObjects
print(array.last) //the object we want will be the last one loaded
})
} else {
print("search second section")
let q = uidNode.queryLimited(toLast: UInt(index) )
q.observeSingleEvent(of: .value, with: { snapshot in
let array = snapshot.children.allObjects
print(array.first) //the object we want will be the first one loaded
})
}
this method only returns 1/2 of the list so it's a much more manageable amount of data.
If you are talking about your authenticated users, the only way to retreive a list of them is by calling the corresponding admin function and applying your logic to it afterwards.
Another way could be writing a trigger for your authentication and store the userId with an incrementing number (and maybe save a totalUser field), then you only need to generate a random number and access said user.

Javascript: Validating if form entries are already submitted to proceed

so I´m working with this: A form where user(workID and name) submits a claim with a date, positioID=secuence. User may have more than 1 secuence and claims are done with one or more dates. So a user may have a claim for 6/7/2017 and secuence=22. Also user may submit a claim with same date (6/7/2017) with secuence=9. User may even submit 2 diferent dates, with different secuences.
Need to validate if user has already submitted a claim for a Date, and secuence. So claims are not duplicated and an alert is triggered if it is already claimed.
To work this out: I´m doing a table/matrix where each secuence is assigned to a date already submitted. The objective is to get many date objects with each assigned secuence. So next entry is compared.
So first step:
claimList.get({workID: $rootScope.workID}, function(response) {
listByDate = [];
var validateList = response.body;
validateList.forEach(function(response){
listByDate.push({
key1: 'date',
key2: 'Secuence',
value1: response.date,
value2: response.secuence
});
}
BUilding this matrix is quite difficult
next step would be a foreach and conditional.
I will assume that data you're trying to store in is inside an object:
data = { date: x, sequence: y }
and data that you have already stored is inside an Array called dataList;
You should just check dataList for those values, if you can't find them it means you're safe and you can proceed by publishing a different and unique entry.
You should code something like the following
var occupiedSlot = dataList.find(
function(elementOfDataList) {
return elementOfDataList.date === data.date
}
);
if(occupiedSlot) alert('You've already published an entry for this date!');
If you need to publish more entries, you can repeat this script inside a function for every entry that you need to check.

Display different text everytime you call onclick function

I have this code where I am trying to pull users from my firebase database:
function pullFromDB(){
usersRef.on('value', function(snapshot) {
function next_user(){
for (user in snapshot.val().users){
document.getElementById("users").innerHTML = user
}
}
So far it will return just one of the users as I believe it must be going through the whole users array and then putting the last name into the "users" element.
How can I iterate to the next item in the array and display a different name every time I click a button?
I have no idea what's return from DB but first try the console.log() to see what's the type of result. This will give you the answer if you are working on array or other data type.
Then if it's an array, your code:
for (user in snapshot.val().users){
document.getElementById("users").innerHTML = user
}
It iterates the whole array and .innerHTML puts user string as the last iteration. If you want to change it each time you click a button you need a variable that will contain inteager of index that's currently aplied to id="users".
Then for each click you need to increase the variable by one.
Here is an example of working with arrays in JS. http://www.w3schools.com/js/tryit.asp?filename=tryjs_array_element
Your are iterating through the whole array and only the last one is possible shown. You just need to assign an index and use it.
I don't know your remaining code, but by the given information, this should to the trick:
i = 0;
function pullFromDB(){
usersRef.on('value', function(snapshot) {
lastnames = Object.keys(snapshot.val().users); // get all keys, in your case the last names
function next_user(){
user = lastnames[i];
document.getElementById("users").innerHTML = user;
i++; // increase after click
// when you want to access more information of the user, you can do it like this (as an example)
// user_id = snapshot.val().users[user].id;
}

Assigning multiple variables from a looping prompt input in Javascript?

I'm writing a very simple program, which asks for a number of names depending on how many tickets are needed. I cannot find a way to change the variable that the prompt input is assigned to every time the loop runs. Is there a way to do this? Below is the current loop I'm using.
while (ticketsNeeded != 0) {
name = prompt("Enter the name of attendee #" + ticketsNeeded);
ticketsNeeded--;
}
For example, if three tickets are needed, the user will be prompted for three different names; however, they are all saved to the same variable and I'd like to have them uniquely assigned so I can later use them.
An array will solve your problem:
var names = []; // initialize empty array
var ticketCounter = 0;
while (ticketsNeeded != 0) {
names[ticketCounter++] = prompt("Enter the name of attendee #" + ticketsNeeded);
ticketsNeeded--;
}

Writing a function in two different ways: one way results in a TypeError and the other does not. Why?

I've come across an issue I don't understand what's going on. Here's the setup: the user enters the screen and inputs a last name. I take the last name and search a phone book (the entire phone book has been retrieved when the user enters the screen so it's just sitting there as a big, fat JavaScript array).
Let's assume each element of the phone book object consists of: a last name, first name and phone number. Now, I'll take the last name inputted by the user and loop across the phone book looking for the last names that match. I'll then push each matching element into an array and display that array to the user.
I've written the method to do this in two different ways. In the first way it returns the list of objects. In the second way (my preference), a TypeError is thrown.
Here is the first approach
$scope.getMatchingLastNames = function(){
for(i=0; i<$scope.phoneBook.length; i++){
if($scope.lastName==$scope.phoneBook[i].lastName){
$scope.filteredArray.push($scope.phoneBook[i]);
}
};
The second approach:
$scope.getList = function(){
$scope.filteredArray = getLastNames($scope.lastName,
$scope.phoneBook, $scope.phoneBook.length);
}
Which calls
function getLastNames(lastName, phoneBook, length)
{
var filteredArray = [];
for(var i=0; i<length; i++){
if(lastName==phoneBook[i].lastName){
filteredArray.push(phoneBook[i]);
}
}
return filteredArray;
}
When I run the second approach I'll get an error in Chrome console as follows:
TypeError: Cannot read property 'lastName' of undefined
And the error points to the if condition:
if(lastName==phoneBook[i].lastName)
Can someone explain to me why the second approach is resulting in an error?
Thanks.
Since what you are trying to achieve is to filter a list of results, I suggest you use angularJs filters
I prepared a jsfiddle for you with a simple example:
https://jsfiddle.net/fb0r7z0q/
This is the key line:
<li ng-repeat="entry in phonebook | filter:qname">
qname being your $scope.lastName

Categories

Resources