I am trying to create sample data to test a form Grid. And am using the following function to try and create the data to send to my grid.
// populateFields: Populates data n times a record of data for the SSM form.
// #params: n, fips, products
// #returns: fields
populateFields(n, fips, products) {
var data = [];
var fields = this.getFields();
for(i = 0; i < n; i++) {
var x = {fields[0]: false,
fields[1]: fips[getRandomInt(0, fips.length())],
fields[2]: products[getRandomInt(0, products.length())],
fields[3]: getRandomInt(0, 100)};
data.push(x);
}
return data;
}
Nothing gets populated when I call it. I get an error saying fields[0]: false needs [ token.
Note: This is part of a class, I don't think that matters.
I am not sure if you want to see how I call it.
Is it because of jQuery, as in what I am passing the array to.
To use a variable as a property key it has to be enclosed in brackets:
{
[fields[0]]: false
//...
}
Otherwise it would try to use field[0] as an identifier itself, and some characters like [ arent allowed in identifiers (cause they are used for property access). (They are allowed in property names though, so { "field[0]": false } would work syntactically, but that makes little sense).
Related
function Checkout(Payment_Type, Tip_Amt){
var Cust_Order = [];
readRecords(Order_Data,{},function(Rec){
for (var i = 0; i < Rec.length; i++) {
appendItem(Cust_Order, Rec[i].Table);
appendItem(Cust_Order, Rec[i].Type);
appendItem(Cust_Order, Rec[i].Item);
appendItem(Cust_Order, Rec[i].Price);
}
console.log(Cust_Order);
});
}
This is part of a restaurant ordering app I have to build for uni. I've saved the customers order in a data set and now I wish to read from that dataset and get the order to be able to calculate the bill and produce an itemised bill
WARNING: Line: 176: readRecords() table parameter value ([object Object]) is not a string.ERROR: Line: 176: TypeError: e.replace is not a function. (In 'e.replace(m,"-")', 'e.replace' is undefined)
Well, for one, your code is really botched. The table name in readRecords isn't a string, and you don't actually need to loop through every entry in the bill to get everything. The returned records are formatted as an object.
function Checkout(Payment_Type, Tip_Amt){
var Cust_Order = [];
readRecords("Order_Data",{},function(Rec){
// Use Rec to get the bill after this line.
console.log(Rec);
}
});
}
From there, you could effectively give them an itemized bill. Just make sure that you clear the table each time you get a new customer.
The Problem is the following:
I have a JSON file that has objects with the following name: "item0": { ... }, "item1": { ... }, "item2": { ... }. But I can't access them when going through an if method.
What I've done so far:
$.getJSON('/assets/storage/items.json', function(data) {
jsonStringify = JSON.stringify(data);
jsonFile = JSON.parse(jsonStringify);
addItems();
});
var addItems = function() {
/* var declarations */
for (var i = 0; i < Object.keys(jsonFile).length; i++) {
path = 'jsonFile.item' + i;
name = path.name;
console.log(path.name);
console.log(path.type);
}
}
If I console.log path.name it returns undefined. But if I enter jsonFile.item0.name it returns the value. So how can I use the string path so that it's treated like an object, or is there an other way on how to name the json items.
As others stated 'jsonFile.item' + i is not retrieving anything from jsonFile: it is just a string.
Other issues:
It makes no sense to first stringify the data and then parse it again. That is moving back and forth to end up where you already were: data is the object you want to work with
Don't name your data jsonFile. It is an object, not JSON. JSON is text. But because of the above remark, you don't need this variable
Declare your variables with var, let or const, and avoid global variables.
Use the promise-like syntax ($.getJSON( ).then)
Iterate object properties without assuming they are called item0, item1,...
Suggested code:
$.getJSON('/assets/storage/items.json').then(function(data) {
for (const path in data) {
console.log(data[path].name, data[path].type);
}
});
What you want is to use object notation using a dynamic string value as a key instead of an object key. So, instead of using something like object.dynamicName you either have use object[dynamicName].
So in your example it would be like this.
path = 'item' + i;
jsonFile[path].name
I'm afraid you cannot expect a string to behave like an object.
What you can do is this:
path = `item${i}`
name = jsonFile[path].name
I have a web app that tracks your purchases and displays different statistics. In one of the pages I have jQuery ajax requests that load a user's purchases from an API call. Then all the purchases are put into a global array, called G_PURCHASES, as JavaScript objects.
So far so good. Then I call a function that uses jQuery's Deferred() to make it chainable; it iterates G_PURCHASES and gets all distinct purchase.item.category's (take a look at the purchase object's relevant structure) by checking if G_PURCHASES[i].item.category is included in another global array called G_CATEGORIES by using Array.includes(). And if it is not then push() it into G_CATEGORIES.
The error I have a problem with is that even after a category object has been pushed into the G_CATEGORIES array, the Array.includes() check still returns false, every time. Check the relevant code and output to clear it up.
// Relevant structure of the purchase object
purchase = {
item: {
category: {
categoryID: int,
name: string
}
}
// Relevant code
var G_PURCHASES = []; // array declared globally
// it is successfully filled with #purchase objects from another function
var G_CATEGORIES = []; // array declared globally
// to be filled by #LoadAllCategories
var LoadAllCategories = function() {
// make a jQuery Deffered
let func = $.Deferred(function() {
let allP = G_PURCHASES; // make a shortcut
let allC = C_CATEGORIES; // make another shortcut
for (var i = 0; i < allP.length; i++) {
// get whether the current purchase.item.category
// already exists in allC array
let exist = allC.includes(allP[i].item.category);
// console.log the above result
console.log('i = ' + i + ', category exists = ' + exist);
// if it doesn't exist then push it in
if (!exist) allC.push(allP[i].item.category);
}
this.resolve();
});
return func;
}
// Input
G_PURCHASES has 6 #purchase objects with 3 unique item.category 'ies
// Output
i = 0, category exists = false
i = 1, category exists = false
i = 2, category exists = false
i = 3, category exists = false
i = 4, category exists = false
i = 5, category exists = false
// Result
G_CATEGORIES contains duplicate categories
I tried to use Array.indexOf() and jQuery's $.inArray() with no success. No matter what I console.log() I can't seem to find where the error lies. So, if you can tell me why does Array.includes() doesn't work inside this for loop I will find you and I will buy you a beer!
Well includes checks for referential equality, so there might be two objects with same properties and values, but still they are different objects, thus their reference is not equal. You probably want to check every category object for their categoryID and name manually to find duplicates.
I am having trouble getting data from the nested pointers in my array of pointers from a query. I have an array of pointers like so: [{"__type":"Pointer","className":"QuizData","objectId":"rmwJrV55c7"},{"__type":"Pointer","className":"QuizData","objectId":"2132q8i9np”}, etc…]
That QuizData class also has a column named “ad” which is a Pointer to the “Ads” class. I can get the QuizData in a query using the following include statements on my query like so:
var __quizAdQueueQuery = new Parse.Query(QuizAdQueue);
__quizAdQueueQuery.equalTo("user", __request.user);
__quizAdQueueQuery.include("quizAdArr”);
__quizAdQueueQuery.include(["quizAdArr.QuizData"]);
BUT Neither of these or both combined don’t work as when I try to get column data from the ad it’s always undefined:
__quizAdQueueQuery.include(["quizAdArr.QuizData.ad"]);
__quizAdQueueQuery.include(["quizAdArr.QuizData.Ads"]);
This is my return from that query, where the column data "mediaType" that I am trying to access is always undefined:
return __quizAdQueueQuery.first().then(function(__resultsObj)
{
__quizQueueObj = __resultsObj;
__userQuizQueueArr = __quizQueueObj.get("quizAdArr");
var __quiz;
var __ad;
var __seenAd;
var __lengthInt = __userQuizQueueArr.length;
var __mediaTypeStr = __request.params.mediaType;
var __matchedQuizzesArr = [];
for (var __i = 1; __i < __lengthInt; __i++)
{
__quiz = __userQuizQueueArr[__i];
// console.log('__quiz.get("name") = '+__quiz.get("name"));
__ad = __quiz.get("ad");
// console.log("__ad.id = "+__ad.id);
//THE MEDIA TYPE IS ALWAYS RETURNING UNDEFINED HERE!!!
console.log('__ad.get("mediaType") = '+__ad.get("mediaType")+', __mediaTypeStr = '+__mediaTypeStr);
if (__ad.get("mediaType") == __mediaTypeStr)
{
//put all matches in array to be sorted
__matchedQuizzesArr.push(__userQuizQueueArr[__i]);
console.log("__matchedQuizzesArr.length = "+__matchedQuizzesArr.length);
}
}
return __matchedQuizzesArr;
});
Thanks for any help you can give! I also posted this as a bug in the Parse/Facebook issue reporter but was redirected here, so if this is a bug I can reopen it: https://developers.facebook.com/bugs/923988310993165/
EDIT Here is the updated, working query with nested includes for clarity:
var __quizAdQueueQuery = new Parse.Query(QuizAdQueue);
__quizAdQueueQuery.equalTo("user", __request.user);
__quizAdQueueQuery.include('quizAdArr');
__quizAdQueueQuery.include('quizAdArr.ad');
This should work (you only need to list the column names):
query.include('quizAdArr.ad');
Here's why:
You're querying QuizAdQueue so you don't need to list that
The QuizAdQueue class has an array in quizAdArr so you include it: query.include('quizAdArr');
Each quizAdArr element is a QuizData with an ad so you include it: query.include('quizAdArr.ad');
The issue was that you were including QuizData which is the name of a class and not a column name
I'm creating a very simplified version of a drag and drop shopping cart with jqueryui.
My issue is regarding adding data(id, name, price) to an array.
I tried several methodes of adding the data (also an array) to the main container(array). But I keep getting this error: Uncaught TypeError: undefined is not a function
var data = [];
function addproduct(id,name,price){
//var d = [id,name,price];
data[id]["name"] = name;
data[id]["price"] = price;
data[id]["count"] = data[id]["count"]+1;
console.log(data);
}
the addproduct() function can be called by pressing a button
It is not entirely clear to me what type of data structure you want to end up with after you've added a number of items to the cart. So, this answer is a guess based on what it looks like you're trying to do in your question, but if you show a Javascript literal for what you want the actual structure to look like after there are several items in the cart, we can be sure we make the best recommendation.
You have to initialize a javascript object or array before you can use it. The usual way to do that is to check if it exists and if it does not, then initialize it before assigning to it. And, since you're keeping a count, you also will want to initialize the count.
var data = [];
function addproduct(id,name,price){
if (!data[id]) {
// initialize object and count
data[id] = {count: 0};
}
data[id]["name"] = name;
data[id]["price"] = price;
++data[id]["count"];
console.log(data);
}
And FYI, arrays are used for numeric indexes. If you're using property names like "name" and "price" to access properties, you should use an object instead of an array.
And, I would suggest that you use the dot syntax for known property strings:
var data = [];
function addproduct(id,name,price){
if (!data[id]) {
// initialize object and count
data[id] = {count: 0};
}
data[id].name = name;
data[id].price = price;
++data[id].count;
console.log(data);
}
It looks like what you want is an array of objects, although I would need a more detailed description of your problem to be clear.
var data = []
function addproduct(id, name, price)
{
data.push({'id': id, 'name':name, 'price': price, 'count': ++count});
console.log(data);
}