Parse Database JavaScript and PhoneGap - javascript

I've been working on an restaurant app that should get the menu from an online database.
This is how I currently and "Manually" populate the menu:
Controller.html
$scope.menu = [{
name: 'Espresso',
price: 27,
qty: 1,
desc: "One shot of espresso prepared with 7 grams of ground coffee in a single portafilter. The shot should be 1 ounce of liquid. You have two choices with espresso: ristretto, a very short or “restrained” shot, brewed at less than 2/3 of a demitasse, or luongo, a long pull of espresso brewed so the liquid should be more than 2/3 of a demitasse.",
img: "img/espresso.png",
active: false,
sizes: [{name: "Small", price: 0, active:false},
{name: "Medium", price: 5, active:false},
{name: "Large", price: 10, active:false}],
flavors: [{name: 'Vanilla', price: 8, active: false},
{name: 'Almond', price: 8, active: false},
{name: 'Hazelnut', price: 8, active: false},
{name: 'Caramel', price: 8, active: false}]
}];
However I can't seem to achieve populating this using Parse, how would I approach this using a query as the following (Which is a working query).
Index.html
<script type="text/javascript">
Parse.initialize("vGoJDvwwfZBiUFcwfkee7M5vCqL7lLxCgKIFJXDc", "6VRlos6qppaek1uDPPLqpHtmB3fHefOJMqYJNxj9");
var DrinkMenu = Parse.Object.extend("DrinkMenu");
var query = new Parse.Query(DrinkMenu);
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " items.");
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
alert(object.id + ' - ' + object.get('name'));
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
</script>
You can notice I can get the variables needed for each item, in this case the name of the first result, which I display in an alert.
Any help is appreciated!

After Parse.initialize, create a variable, like this:
var arrMenu = [];
then change the line alert(object.id + ' - ' + object.get('name')); to
arrMenu.push({
name: object.get('name'),
price: object.get('price'),
qty: object.get('qty'),
desc: object.get('desc'),
img: object.get('img'),
active: object.get('active'),
sizes: object.get('sizes'),
flavors: object.get('flavor')
});
I am supposing that you are storing the info in the Parse Collection with the structure you mentioned. If it is different, let me know.
And, after the brack the closes the for, you add:
$scope.menu = arrMenu;
I hope it helps!

Related

How to get info from object on click

So i made this object and i'm appending to the html. I would like to make a js function that would give me the info from the object upon clicking the element. So when i click element named car it would give me the name car in js.
var ItemCollection =
[
{
Name: 'IVY PARK SHOES',
Price: 160,
Picture: 'https://assets.adidas.com/images/w'
},
{
Name: 'JOGGER SHOES',
Price: 160,
Picture: 'https://assets.adidas.com/images/w_840,h_840,f_'
},
{
Name: 'ULTRABOOST SHOES',
Price: 200,
Picture: 'https://assets.adidas.com/images/w_840,h_840,f_auto,q'
},
{
Name: 'NITE SHOES',
Price: 130,
Picture: 'https://assets.adidas.com/images/w_840,h_840,f_a'
},
];
i know the one bellow will give me the items index but i'd like it to give me name/price or picture. Also the it doesn't have to be alert the alert is just to see if it works.
var g = document.getElementById('Collection');
for (var i = 0, len = g.children.length; i < len; i++) {
(function(index){
g.children[i].onclick = function(){
alert(index);
}
})(i);
}

How to properly check if a name is available in an array made of objects (record collection)?

so my plan for this was to have a message appear asking someone to type in a student name. Javascript would look through a record, which is in a seperate JS file, and then output that in the message variable. If suppose the student didn't exist, the output message would be the alert box in the else statement.
Heres a record of the students:
var students=[
{
name:'Chris',
track:'IOS',
achievements:'100',
points:'1000'
},
{
name:'John',
track:'Web Design',
achievements:'90',
points:'1000'
},
{
name:'Brent',
track:'Front-End',
achievements:'70',
points:'1000'
},
{
name:'Josh',
track:'Full-Stack',
achievements:80,
points:'1000'
},
{
name:'Nick',
track:'AI',
achievements:'60',
points:'1000'
}
];
var message="";
var search=prompt("Type name of student");
while (search!=="quit") {
for (var i=0; i<students.length; i+=1) {
var studentName=students[i].name;
if (studentName===search) {
message+="<h1>"+studentName+"</h1>";
message+="<p>"+student[i].track+"</p>";
message+="<p>"+student[i].achievements+"</p>";
message+="<p>"+student[i].points+"</p>";
break;
} else {
alert("That student does not exist. Try again");
break;
}
}
search=prompt("Type name of student");
}
print(message);
When I try this code, it asks me for the student's name and then says he/she is not available. Apparently, the determination that the student is not in the list should only be made after the loop has finished checking all the students. Then, and only if nothing was found, should the failure message be output.
The problem for me, conceptually, is that the final value of the variable, studentName, after the for loop ends will be the name property of the last object in the array. So how would I redesign my for loop then?
How can I redesign my code to accomplish just that?
You can try this,
var message="";
var search=prompt("Type name of student");
while (search!=="quit") {
// we will get result if any one student name matches
var result = students.find((student) => student.name === search);
if (result) {
message+="<h1>"+result.name+"</h1>";
message+="<p>"+result.track+"</p>";
message+="<p>"+result.achievements+"</p>";
message+="<p>"+result.points+"</p>";
}
else {
alert("That student does not exist. Try again");
}
search=prompt("Type name of student");
}
print(message);
you can filter your list first and then check it like
const students = [
{
name: 'Chris',
track: 'IOS',
achievements: '100',
points: '1000'
},
{
name: 'John',
track: 'Web Design',
achievements: '90',
points: '1000'
},
{
name: 'Brent',
track: 'Front-End',
achievements: '70',
points: '1000'
},
{
name: 'Josh',
track: 'Full-Stack',
achievements: 80,
points: '1000'
},
{
name: 'Nick',
track: 'AI',
achievements: '60',
points: '1000'
}
];
let search = prompt('Type name of student');
while (search !== 'quit') {
const filteredList = students.filter(function(student) {
return student.name === search;
});
let message = '';
if (filteredList.length > 0) {
for (const student of filteredList) {
message += '<h1>' + student.name + '</h1>';
message += '<p>' + student.track + '</p>';
message += '<p>' + student.achievements + '</p>';
message += '<p>' + student.points + '</p>';
}
alert(message);
} else {
alert('That student does not exist. Try again');
}
search = prompt('Type name of student');
}
In order to avoid looping through the entire array each time you want to show a message for the user, making an object from the array is the best approach.
for example:
var students=[
{
id: 1,
name:'Chris',
track:'IOS',
achievements:'100',
points:'1000'
},
{
id: 2,
name:'John',
track:'Web Design',
achievements:'90',
points:'1000'
},
{
id: 3,
name:'Brent',
track:'Front-End',
achievements:'70',
points:'1000'
},
{
id: 4,
name:'Josh',
track:'Full-Stack',
achievements:80,
points:'1000'
},
{
id: 5,
name:'Nick',
track:'AI',
achievements:'60',
points:'1000'
}
];
const arrayToObject = (array) =>
array.reduce((obj, item) => {
obj[item.id] = item
return obj
}, {});
const studentsObject = arrayToObject(students);
console.log(studentsObject);
console.log(studentsObject[2]);

add a field and update another in array of objects

A query returns an array of objects from a collection. I want to add a field to each of the objects in that array, and update another field in every object of the array.
Products array before update:
[{ _id: 58d895b8ffc0346230a43a89,
event: 'Junior Girls 12s',
group: 'nonpro',
price: 50,
day: 'Friday' },
{ _id: 59d895b8ffc0346230a43a89,
event: 'Junior Girls 14s',
group: 'nonpro',
price: 50,
day: 'Friday', }]
My code to update the array of objects:
//add the field and changed price if late fee applies
for(var i = 0; i < products.length; i++) {
products[i].field = registered.frifield;
console.log(products[i].field);
if(settings.latefeeamt > 0 && settings.frilatefee === true) {
products[i].price += settings.latefeeamt;
}
console.log(products[i]);
console.log(events.friday);
}
How products array SHOULD look after update:
[{ _id: 58d895b8ffc0346230a43a89,
event: 'Junior Girls 12s',
group: 'nonpro',
price: 60,
day: 'Friday',
field: 'Main' },
{ _id: 59d895b8ffc0346230a43a89,
event: 'Junior Girls 14s',
group: 'nonpro',
price: 60,
day: 'Friday',
field: 'Main' }]
How can I get this to work? It console.logs the correct field inside the loop, but I get the original array when it's done.
As a rule, Don't change the array you are iterating, it's bad practice.
You can use map : array.map
var array = products.map((element, index) => {
element.field = registered.frifield;
if(settings.latefeeamt > 0 && settings.frilatefee === true) {
element.price += settings.latefeeamt;
}
return element
});
This should return an array, inside you will have the updated product list
Hi there i wasn't sure about this portion of code because settings isn't defined
if(settings.latefeeamt > 0 && settings.frilatefee === true) {
products[i].price += settings.latefeeamt;
}
Here you have a code that works i change the condition depending on the day, you can update it depending on your specification hope it helps
var products = [{
_id: '58d895b8ffc0346230a43a89',
event: 'Junior Girls 12s',
group: 'nonpro',
price: 50,
day: 'Friday'
},
{
_id: '58d895b8ffc0346230a43a89',
event: 'Junior Girls 14s',
group: 'nonpro',
price: 50,
day: 'moday',
}];
console.log(products);
for(product of products) {
product.field = 'Main';
if (product.day === 'moday') {
product.price = 30;
}
}
console.log(products);

Display related products in javascript

I need to display related products in javascript on eBay listing.
I have that idea: I keep in array info about other listings like: url, image, price and tags attached to this product.
example:
some_product = [
tags: 'home, garden, kitchen',
url: http://listing.url,
price: 100
],
some_product_2 = [
tags: 'home, lifestyle, books',
url: http://listing2.url,
price: 120
]
and on listing I put code like:
<script type="text/javascript" src="http://domain.com/related_prod.js?keyword=home"></script>
And I expect that showed all the products with "home" in "tags". Can someone direct me to a solution?
First off, this is not a valid JavaScript or JSON:
some_product = [
tags: 'home, garden, kitchen',
url: http://listing.url,
price: 100
],
some_product_2 = [
tags: 'home, lifestyle, books',
url: http://listing2.url,
price: 120
]
The above should be replaced with the { } for objects.
{
some_product: {
tags: 'home, garden, kitchen',
url: http://listing.url,
price: 100
},
some_product_2: {
tags: 'home, lifestyle, books',
url: http://listing2.url,
price: 120
}
}
The above is a JavaScript object now. But this has been made better. Now, this being a pure JSON, it has to be added to a JavaScript variable. Consider this:
var products = {
some_product: {
tags: 'home, garden, kitchen',
url: http://listing.url,
price: 100
},
some_product_2: {
tags: 'home, lifestyle, books',
url: http://listing2.url,
price: 120
}
}
Now using the products, you can loop and put it as a list item.
var products = {
some_product: {
tags: 'home, garden, kitchen',
url: 'http://listing.url',
price: 100
},
some_product_2: {
tags: 'home, lifestyle, books',
url: 'http://listing2.url',
price: 120
}
}
var finalHtml = "";
for (var item in products) {
finalHtml += '<li><a href="' + products[item].url + '">' + item + '<\/a> <br \/>Tags: ' + products[item].tags + '<br \/>Price: ' + products[item].price + ' $</li>';
}
document.getElementById("products").innerHTML = finalHtml;
<ul id="products"></ul>
See the snippet above.
Considering that's not valid JavaScript, we can restructure your code to something more usable for your scenario... Like this:
var products = [
{
name: 'some_product',
tags: ['home', 'garden', 'kitchen'],
url: 'http://example.com/1',
price: 100,
},
{
name: 'some_product_2',
tags: ['home', 'lifestyle', 'books'],
url: 'http://example.com/2',
price: 120,
}
];
From here, we can use Array.prototype.filter to fetch the results based on tags:
function category(tag) {
return products.filter(function(product){
if (~product.tags.indexOf(tag)) return product;
});
}
category('home');
// ...
Example
both Praveen Kumar and Jamen proved to be helpful. I joined their answers to create one code.
var products = [
{
name: 'some_product',
tags: ['home', 'garden', 'kitchen'],
url: 'http://example.com/1',
price: 100,
},
{
name: 'some_product_2',
tags: ['home', 'lifestyle', 'books'],
url: 'http://example.com/2',
price: 120,
},
{
name: 'some_product_3',
tags: ['garden', 'lifestyle', 'books'],
url: 'http://example.com/2',
price: 120,
}
];
var finalHtml = "";
function category(tag) {
return products.filter(function(product){
if (~product.tags.indexOf(tag)) {
finalHtml += '<li><a href="' + product.url + '">' + product.name + '<\/a><br \/>Price: ' + product.price + ' $</li>';
document.getElementById("products").innerHTML = finalHtml;
console.log(product.name);
}
});
}
category('home');
//category('garden');
<ul id="products"></ul>
https://jsfiddle.net/p5x2v2cb/
Thank you for answers.

Access data from an array with jquery

Im trying to loop through an array only i cant seem to extract the data from my array...
http://jsfiddle.net/338Ud/
var listTicker = function (options) {
var defaults = {
list: [],
startIndex: 0,
interval: 3 * 1000,
}
var options = $.extend(defaults, options);
var listTickerInner = function (index) {
if (options.list.length == 0) return;
if (!index || index < 0 || index > options.list.length) index = 0;
var value = options.list[index];
options.trickerPanel.fadeOut(function () {
$(this).html(value).fadeIn();
});
var nextIndex = (index + 1) % options.list.length;
setTimeout(function () {
listTickerInner(nextIndex);
}, options.interval);
};
listTickerInner(options.startIndex);
}
var textlist = new Array({
id: 0,
name: 'Antonia Lallement',
title: '\u003cp\u003e\u003cspan\u003eConsultant\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI started as a resourcer at company three months ago so I\u0026rsquo;m a new team member. Sin...',
image: 'antonia.jpg'
}, {
id: 1,
name: 'Camilla Gobel',
title: '\u003cp\u003e\u003cspan\u003eBusiness Manager\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI joined company in 2011. As a multilingual Consultant, my initial focus was the provisi...',
image: 'camilla.jpg'
}, {
id: 2,
name: 'Mark Dorey',
title: '\u003cp\u003e\u003cspan\u003eDiscipline Manager (Process, Subsea, Project, Safety)\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eWhen I joined company I started as a resourcing specialist and worked across Search and ...',
image: 'mark.jpg'
}, {
id: 3,
name: 'Sadia Butt',
title: '\u003cp\u003e\u003cspan\u003eDiscipline Manager (Mechanical, Piping, Structural)\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI couldn\u0026rsquo;t have asked for a better company to work for! After working as a resourc...',
image: 'sadia.jpg'
}, {
id: 4,
name: 'Samantha Linnert',
title: '\u003cp\u003e\u003cspan\u003ePayroll Assistant\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI began at company as an operations assistant learning to spec CVs and post jobs. Shortl...',
image: 'samantha.jpg'
}, {
id: 5,
name: 'Simon Cottenham',
title: '\u003cp\u003e\u003cspan\u003eConsultant, Middle East\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI have been with company for exactly one year now, I never would have believed that I wo...',
image: 'simon.jpg'
}, {
id: 6,
name: 'Vicky Spencer',
title: '\u003cp\u003e\u003cspan\u003ePayroll Manager\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI started my career at company in July 2012 initially covering maternity leave, managing...',
image: 'vicky.jpg'
});
$(function () {
listTicker({
list: textlist,
startIndex: 0,
trickerPanel: $('.textbox'),
interval: 3 * 1000,
});
});
you are adding object to a html .... use . operator to get the actual values
....
options.trickerPanel.fadeOut(function () {
$(this).html(value.id).fadeIn();
//--------^^^----here
}
i am taking id from the object and showing it in the div.. you can add whatever you need there..
$(this).html(value.title).fadeIn(); //to get title
fiddle here
$.each(textlist, function(index, value){
//do stuff with your array
});
Pasting just the diff, i tried to get the data here below.
From the code above.
options.trickerPanel.fadeOut(function () {
$(this).html(value).fadeIn();
});
The diff,
options.trickerPanel.fadeOut(function () {
$(this).html(value.bio).fadeIn();
});
The difference, is value is the entire array object being passed to the fadeOut function, accessing each elements in the array gives the result.

Categories

Resources