How to generate an array of arrays in Javascript? - javascript

So given:
var person = {name: "", address: "", phonenumber: ""}
I want to create a loop to receive user input (until they decide they don't want to input anymore information and input nothing or click cancel). I'd also like to use the person object as a prototype.
So I guess an object just to store the name/address/phone number of an arbitrary number of people. My logic for this would be to dynamically add an entire array to an object for every iteration of my loop. My code looks something like this:
var person = {name: "", address: "", phonenumber: ""}
var customer = []; //used to store each person
var input = "x";
//loop prompting user to input name/address/phone number
for(var i = 0; input != ""; i++){
var input = prompt("Input separated by commas");
//example input: mike, main, 123456789
var results = input.split(", "); //create an array from the input
//move input into the person array.
//person to look like {name = "mike", address = "main", phone = "123456789"}
person.name = results.shift();
person.address = results.shift();
person.phone = results;
customer[i] = person;//store the person array into the customer array.
}
I've been trying to dynamically generate something like this:
customer =
[{name, address, phone},
{name, address, phone},
{name, address, phone}]
and then be able to access it and print it. i've been trying to access it with
console.log(customer[0].phone);
unfortunately im getting an error.
sorry for my error, console.log prints nothing so it seems like there's nothing stored in customer[0].phone.
i can't get access to any of the data that i've prompted the user for and saved in variables. when i use the alert function all i get is a blank box. whenever i try to print customer i get the message [object Object]or something along those lines

var customer = [];//create array
var person = {};// create object
var input = prompt("...");//your prompt
var results = input.split(", "); //create an array from the input
person.name = results[0];//add result with 0 index
person.address = results[1];//add result with 1 index
person.phone = results[2];//add result with index 2
customer[0] = person;//add the person object to the array.
The above code should do as you wish. I'm having a hard time seeing why you would iterate a prompt to the same user?? So try this first then go on.
http://jsfiddle.net/zkc2swmp/1/
Don't go irratating your users with prompt boxes, use a form. Also don't iterate something like that, and your condition in the for loop basically creates an infinite loop which is also bad
My code could be a lot better, such as if conditions, and exactly how to use this with a form. Though frankly it seems as though you are far from that. So I've started you off, try it and see if you can implement this the way you want, then comment with suggestions for helping you do something else.

First of all, every time you are assigning person to customer i.e.
customer[i] = person;
all other objects are getting modified as your breaking point is input== "" so all objects are modified with null values.
in start you are defining property as "phonenumber" and in the end u r putting value in "phone".
correct code shud be :
var customer = []; //used to store each person
var input = "x";
//loop prompting user to input name/address/phone number
for(var i = 0; input != ""; i++){
var input = prompt("Input separated by commas");
//example input: mike, main, 123456789
var results = input.split(", "); //create an array from the input
var person = {};
person.name = results.shift();
person.address = results.shift();
person.phone = results;
customer[i] = person;//store the person array into the customer array.
}

Related

Trying to use input from prompt as object value within a function

Please be aware that I have only learned how to use objects this morning, so this is mainly an exercise to play around with this.
I was able to set up an array with a list of students. Each student is an object with multiple properties. I was also able to add another property and value to each object within the array using a for loop.
What I'm trying to do now is prompt the user to enter an object name "student1, student2, etc." I'm trying to use the value of that prompt, saved as var studentSelected, in the function reportStudentInfo(info).
What does work: If i get rid of the variable "selectedStudent", and I specifically decide to put in an object value student1, student2, etc. it works as expected.
What I don't understand:
I'm guessing the value of the prompt changes to a string from the prompt and it seems to mess up the value of what the object is, even though the prompt input might be: "student1" the function isn't reading it as student1. It returns an undefined value for each of the object property values.
I really hope I asked a clear enough question. Thanks for any help.
Logan
link to JSFiddle: https://jsfiddle.net/lwood3499/aevsbrk8/
var selectedStudent = prompt("Which student do you want to see the results for Test #1?");
reportStudentInfo( selectedStudent.name + " : " + selectedStudent.test1 );
After
var selectedStudent = prompt("Which student do you want to see the results for Test #1?");
selectedStudent is a string entered at the prompt. It does not have name or test1 properties.
If selectedStudent object already exists, you can do
var selectedStudent.name = prompt("Which student do you want to see the results for Test #1?");
or
var studentName = prompt("Which student do you want to see the results for Test #1?");
Update:
var selectedStudent = prompt("Which student do you want to see the results for Test #1?");
var found = null;
for (var iter = 0; iter < list.length; iter++) {
if (selectedStudent == list[iter].name) {
found = list[iter];
break;
}
}
if (found) {
reportStudentInfo(found.name + " : " + found.test1 );
} else {
alert(selectedStudent + " not found");
}

Display the results of an array on another page

I'm trying to load an array from one page and then have the results appear on another using javascript/jQuery. So a user will make a selection from a dropdown. Based on this dropdown the "customers" address, phone, email, etc. will appear in a text field. I'm trying to store those results in to the array (name | address | etc in one index of the array), display the result on the second screen, and then allow the user to add more names if necessary.
At the moment I'm trying to use localStorage to store the values and then JSON.stringify to convert the results so they can be stored in the array.
I think these are all of the pertinent lines:
var customerArray = [];
var getName = $('#DropDownList1').val();
var getAddress = $('#DataList1').text().trim();
var getPhone = $('#DataList2').text().trim();
var getEmail = $('#DataList3').text().trim();
//store the variables
localStorage.setItem("name", getName);
localStorage.setItem("address", getAddress);
localStorage.setItem("phone", getPhone);
localStorage.setItem("email", getEmail);
//user will click #btnAdd to add the customers information
//into customerArray[]
$("#btnAdd").click(function () {
var setName = localStorage.getItem("name");
var setAddress = localStorage.getItem("address");
var setPhone = localStorage.getItem("phone");
var setEmail = localStorage.getItem("email");
var post = setName + setAddress + setPhone + setEmail;
if (customerArray.length == 0) {
customerArray[0] = post;
} else {
for (var i = 1; i < customerArray.length; ++i) {
//store results of 'post' into the array
customerArray.push(post);
localStorage.setItem("storedArray",JSON.stringify(customerArray));
}
}
}); //end #btnAdd click event
Form here the 2nd page will load with a text field that will (should) display the results of the array (customerArray). Unfortunately I can only get 1 value to appear.
At the moment this is the block being used to display the results:
$('#tbContactList').val(JSON.parse(localStorage.getItem("storedArray")));
If it matters I'm writing the application using Visual Studio Express 2012 for Web. The data that initially populates the customers information comes from a database that I've used ASP controls to get. I'm confident there is a perfectly simple solution using ASP/C# but I'm trying to solve this problem using javascript/jQuery - I'm more familiar with those languages than I am with C#.
Thank you.
Use Array.join() to turn your array into a string to store.
Then use Array.split() to turn your string back into an Array.
Example
var arr=['name','email','other'];
var localStorageString=arr.join(',');
localStorage.setItem('info',localStorageString);
var reassemble=localStorage.info.split(',');
for(var i=0;i<reassemble.length;i++){
document.body.innerHTML+=reassemble[i]+"<br/>";
}
http://jsfiddle.net/s5onLxd3/
Why does the user have to leave the current page though? IS a tabbed/dynamic interface not an option?

Javascript: Using user input to search an array of arrays

Maybe I'm structuring this code wrong (first time working with Javascript) but I want to take user input and search an array of arrays to check if an array with that name exists.
I first tried using the eval() function which I've been told isn't good but it works when there is a match, failing when a match that doesn't exist though.
The basic premise of the program is there is an array containing locations which are subsequently arrays containing food items. The user enters the name of a food item and where they want to put it and it will create an object of food, insert that object into the right location within the arrays, and also input the item onto a list displayed in html.
Here's all the code so far:
var fridge = [];
var freezer = [];
var pantry = [];
var locations = [fridge, freezer, pantry];
function Food(name, location, locationName){
this.name = name;
this.location = location;
this.locationName = locationName;
this.displayName = function(){
alert(this.name);
};
};
function createFood(){
var name = prompt("Enter the items name:");
var locationName = prompt("Enter a location to store it:")
var location = eval(locationName);
while(locations.indexOf(location) == -1){
alert("This is not an actual location.");
locationName = prompt("Please enter another location:");
location = eval(locationName);
};
var x = new Food(name, location, locationName)
function insertFood(Food){
var a = locations.indexOf(Food.location);
locations[a].push(Food);
var list = document.getElementById(Food.locationName + "_items");
var li = document.createElement("li");
li.innerHTML = Food.name;
list.insertBefore(li, list.lastChild);
};
insertFood(x);
};
Please let me know if this is structured wrong cause this was my idea for structuring at first glance.
Thanks!
As suggested above, it would be best to make locations an object, so that you can have a key (a string) pointing to the array with the same name.
var fridge = [];
var freezer = [];
var pantry = [];
var locations = {
"fridge":fridge,
"freezer":freezer,
"pantry":pantry
};
The benefit of this is that you don't need to have a locationName, since it never really comes into play. All you would need is to check if the locations object has a property by the same name as the user input, using the native hasOwnProperty function. Something like:
if(!locations.hasOwnProperty(userInputLocation))
alert("That is not a designated location");
Then your Food constructor also becomes simpler, and needs only name and location properties:
function Food(name, location){
this.name = name;
this.location = location;
}
You can also then call any specific location directly by its name (if you're going to declare it globally as you did in your code), or more appropriately (if you declare the arrays inside the object as in SGD's code) by locations[location], where location is just a string holding either "freezer" or "pantry" or "fridge". You can also call the array via locations[someFood.location].
Anyway I am not much for prompts and alerts (let alone eval), so I created a jsBin using input fields, you can check it out here: http://jsbin.com/pamoquwuhu/1/edit
edited to add:
If the goal is that you later want to find food by its name in all the locations it is saved in, it would be best to add/push foodObj.name instead of the whole foodObj in locations[location]. Then you can use the native for(property in object) loop on the locations object to see where all a given food might be stored, and push it into a results array. So your findFood function might contain the following (assuming food is the user input string of of food name to search for:
var results = [];
for(var loc in locations){ // loops through the property names in `locations`
if(locations[loc].indexOf(food)>=0)
results.push(loc);
}
if(!results.length){
alert(food+' was not found');
else
alert(food+' was found in '+results.toString());
Assuming the same food can be stored in multiple locations and that you want to find a given food by its name, your food object's location property would become less important (or possibly useless).
You are using Food as function/constructor and as parameter name (that should not be the issue however but can cause trouble later) and you are never calling insertFood. Also locations should rather be object than array so that you can access the sub arrays as you do in your code.
var locations = {fridge : [], freezer:[], pantry:[]];
function Food(name, locationName){
this.name = name;
this.locationName = locationName;
this.displayName = function(){
alert(this.name);
};
};
function createFood(){
var name = prompt("Enter the items name:");
var locationName = prompt("Enter a location to store it:")
while(locationName in locations){
alert("This is not an actual location.");
locationName = prompt("Please enter another location:");
};
var x = new Food(name, locationName)
function insertFood(food){
locations[food.locationName].push(food);
var list = document.getElementById(food.locationName + "_items");
var li = document.createElement("li");
li.innerHTML = food.name;
list.insertBefore(li, list.lastChild);
};
// call the method now?
insertFood(x);
};
createFood();

Accessing Properties in Array of Arrays? (Javascript)

var person = { firstname: "", lastname: "", email: "" };
var student = Object.create(person);
var i = 0;
var flag = true;
//create array of arrays. similar to a database. Receive unspecified number
//number of inputs from user
while (flag) {
var input = prompt("Please enter fname, lname, and email");
//Sample input: John, Doe, abcd#efg.com
var results = input.split(", ");
student[i]=({
firstname: results.shift(),
lastname: results.shift(),
email: results,
});
i++;
console.log(student[i].firstname);//testing code. returns student[i] is undefined
console.log(student[0].firstname);//testing code. returns John.
flag = confirm("Do you want to continue?");
};
When I try to run this code I get the error student[i] is undefined.
Even though I pretty much set the values of student[i] in the code directly above it.
However, when I try to output student[0].firstname I will get John.
EDIT: Even with
console.log(student[i].firstname);
placed in front of the i++ it isn'tworking
You're incrementing the i and then you query the array. So when you put in a new item lets say the index 0, when you query the result back, you'll actually query the student 1. Move the i++; down after the console.log.
Look at what you do:
student[i]=({
...
i++;
...
console.log(student[i].firstname);
So you set student[i]. Then you increment i, so it is no longer the same value as it was before. Then you try to use that value to access a property of student, which doesn't exist because you haven't set it.
You need to reorder your calls. I imagine i++ should be at the very end of the block.
After you assign student[i] you call i++. This sets i=1. You have not set students[1] to any value.
I believe what you want to do is make a students array, and then push new instances to that.
var students = [];
var flag = true;
//create array of arrays. similar to a database. Receive unspecified number
//number of inputs from user
while (flag) {
var input = prompt("Please enter fname, lname, and email");
//Sample input: John, Doe, abcd#efg.com
var results = input.split(", ");
students.push({
firstname: results.shift(),
lastname: results.shift(),
email: results[0],
});
console.log(JSON.stringify(students)); //testing code
flag = confirm("Do you want to continue?");
};
That i++; above console.log(student[i].firstname);//testing code. returns student[i] is undefined is setting i = 1.
Move the i++ after your logging and change the way results is accessed
var results = input.split(", ");
student[i]=({
firstname: results[0],
lastname: results[1],
email: results[2]
});
console.log(student[i].firstname);//testing code. returns student[i] is undefined
console.log(student[0].firstname);//testing code. returns John.
i++;

Filling arrangement from a database

I need to fill an array with each of the values ​​for "name" and "nickname" taken from a SQLITE database and show it in an alert.
This is for a project written in JavaScript in titanium appcelerator.
This is the code:
var fightersRS = db.execute('SELECT * FROM fighters');
var setFighters = [];
while (fightersRS.isValidRow())
{
var name = fightersRS.fieldByName('name');
var nickname = fightersRS.fieldByName('nickname');
setFighters.push = {
name: name,
nickname: nickname
};
fightersRS.next();
}
alert(setFighters);
The idea is that the alert displays all comma separated values, for example:
"muhammad ali, rocky balboa, ten shin han, etc ...."
How I can do it? my code does not work.
Change your code as follows
var fightersRS = db.execute('SELECT * FROM fighters');
var setFighters = [];
while (fightersRS.isValidRow())
{
var name = fightersRS.fieldByName('name');
var nickname = fightersRS.fieldByName('nickname');
setFighters.push({"name": name, "nickname": nickname}); //This is the correct syntax for pushing an element to the array
fightersRS.next();
}
You can display the elements using a for loop as follows
for(var i=0; i <setFighters.length;i++){
alert("Name = " + setFighters[index].name + " Nickname= " + setFighters[index].nickname);
}
If you want to display their name with comma, try the following
var fightersRS = db.execute('SELECT * FROM fighters');
var setFighters = [];
while (fightersRS.isValidRow())
{
var name = fightersRS.fieldByName('name');
setFighters.push(name);
fightersRS.next();
}
var fighters = setFighters.join(",");//Joining the array elements with comma
alert(fighters); //Will display all names with a comma
Look at javascript join method
Use a for loop or inside the while loop only create a string appending all the values with comma.
Fetching all the data from an array with comma is not possible.
Here's an asccociative array example from stack over flow .. you can have your own for loop or use the while loop you are creating
Associative array and fetching data
Thanks

Categories

Resources