Set object properties in loop parse.com - javascript

I'm using the Parse.com javascript SDK and I'm trying to set some fields of the object in the loop, but only those fields which I am creating in the loop are not getting saved in parse also it is not giving me any error.
CODE:
var room = new Room();
room.id = params.roomId;
var rate = new Rate();
rate.set('room', room);
for (var i = 0; i < 100; i++) {
rate.set("rate" + i, params.price); // this fields are not getting saved
}
rate.save(null, {
success: function(rate) {
params.success(Response.SaveSuccess);
},
error: function(rate, error) {
console.log('ERROR SAVING RATE: ' + error.message);
params.error(Response.InternalServerError);
}
});
After successful response, I can see only room field in database

The way you are trying to set values in rate object seems a little weird. The first argument of "set" method of Parse.Object accepts only column name enclosed in inverted commas. So following is the only solution of updating an object in Parse Js:
rate.set("rate", params.price);
P.S. You need to elaborate what exactly you want to achieve in your code so that a proper solution can be posted.
Thanks

Related

AppLab error e.replace is not a function when reading from data set

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.

Complex JSON obj and jQuery or Javascript map to specific key, value

I am banging my head trying to figure this out. And it should not be this hard. I am obviously missing a step.
I am pulling data from: openaq.org
The object I get back is based on a JSON object.
For now, I am using jQuery to parse the object and I am getting to the sub portion of the object that hold the specific parameter I want but I can't get to the specific key,value pair.
The object does not come back in the same order all the time. So when I tried to originally set up my call I did something like
obj.results.measurements[0].
Well since the obj can come back in an random order, I went back to find the key,value pair again and it was the wrong value, throwing my visual off.
That said, I have looked at use jQuery's find() on JSON object and for some reason can not get what I need from the object I am given by openaq.org.
One version of the object looks like this:
{"meta":{"name":"openaq-api","license":"CC BY 4.0d","website":"https://u50g7n0cbj.execute-api.us-east-1.amazonaws.com/","page":1,"limit":100,"found":1},"results":[{"location":"Metro Lofts","city":null,"country":"US","coordinates":{"latitude":39.731,"longitude":-104.9888},"measurements":[{"parameter":"pm10","value":49.9,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"pm1","value":24,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"um100","value":0,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um025","value":0.28,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um010","value":4.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"pm25","value":41.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"}]}]}
I am trying to get the "pm25" value.
The code I have tried is this:
function getAirQualityJson(){
$.ajax({
url: 'https://api.openaq.org/v2/latest?coordinates=39.73915,-104.9847',
type: 'GET',
dataType: "json"
// data: data ,
}).done(function(json){
console.log("the json is" + JSON.stringify(json));
console.log("the json internal is" + JSON.stringify(json.results));
var obj = json.results;
var pm25 = "";
//console.log(JSON.stringify(json.results.measurements[0]["parameter"]));
$.each(json.results[0], function(i,items){
//console.log("obj item:" + JSON.stringify(obj[0].measurements));
$.each(obj[0].measurements, function(y,things){
//console.log("each measurement:" + JSON.stringify(obj[0].measurements[0].value));//get each measurement
//pm 2.5
//Can come back in random order, get value from the key "pm25"
// pm25 = JSON.stringify(obj[0].measurements[2].value);
pm25 = JSON.stringify(obj[0].measurements[0].value);
console.log("pm25 is: " + pm25); // not right
});
});
//Trying Grep and map below too. Not working
jQuery.map(obj, function(objThing)
{ console.log("map it 1:" + JSON.stringify(objThing.measurements.parameter));
if(objThing.measurements.parameter === "pm25"){
// return objThing; // or return obj.name, whatever.
console.log("map it:" + objThing);
}else{
console.log("in else for pm25 map");
}
});
jQuery.grep(obj, function(otherObj) {
//return otherObj.parameter === "pm25";
console.log("Grep it" + otherObj.measurements.parameter === "pm25");
});
});
}
getAirQualityJson();
https://jsfiddle.net/7quL0asz/
The loop is running through I as you can see I tried [2] which was the original placement of the 'pm25' value but then it switched up it's spot to the 3rd or 4th spot, so it is unpredictable.
I tried jQuery Grep and Map but it came back undefined or false.
So my question is, how would I parse this to get the 'pm25' key,value. After that, I can get the rest if I need them.
Thank you in advance for all the help.
You can use array#find and optional chaining to do this,
because we are using optional chaining, undefined will be returned if a property is missing.
Demo:
let data = {"meta":{"name":"openaq-api","license":"CC BY 4.0d","website":"https://u50g7n0cbj.execute-api.us-east-1.amazonaws.com/","page":1,"limit":100,"found":1},"results":[{"location":"Metro Lofts","city":null,"country":"US","coordinates":{"latitude":39.731,"longitude":-104.9888},"measurements":[{"parameter":"pm10","value":49.9,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"pm1","value":24,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"um100","value":0,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um025","value":0.28,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um010","value":4.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"pm25","value":41.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"}]}]}
let found = data?.results?.[0]?.measurements?.find?.(
({ parameter }) => parameter === "pm25"
);
console.log(found);
You can iterate over measurements and find the object you need:
const data = '{"meta":{"name":"openaq-api","license":"CC BY 4.0d","website":"https://u50g7n0cbj.execute-api.us-east-1.amazonaws.com/","page":1,"limit":100,"found":1},"results":[{"location":"Metro Lofts","city":null,"country":"US","coordinates":{"latitude":39.731,"longitude":-104.9888},"measurements":[{"parameter":"pm10","value":49.9,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"pm1","value":24,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"um100","value":0,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um025","value":0.28,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um010","value":4.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"pm25","value":41.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"}]}]}';
const json = JSON.parse(data);
let value = null;
const measurements = json?.results?.[0]?.measurements ?? null;
if(measurements)
for (const item of measurements)
if (item.parameter === 'pm25') {
value = item.value;
break;
}
if (value) {
// here you can use the value
console.log(value);
}
else {
// here you should handle the case where 'pm25' is not found
}

Javascript - How to pull data from Google Firebase randomly?

I'd like all my Firebase content to load randomly every time you refresh, but I can't seem to get all my Firebase data into a dictionary where I can randomize them.
I have a global array and I'm trying to push my files in there and then iterate through them. But Javascript thinks the array is empty because the timing is off.
var randomStore = new Array;
function homeSetup() {
if(ref.toString() == featuredRef.toString()){
addFeaturedImages();
}
console.log('randomStore length is ' + randomStore.length);
}
function addFeaturedImages(){
featuredRef.on("child_added", function(snapshot) {
var doc = {
// 'name': snapshot.key, //name is the id
'artist': snapshot.val().artist,
'author': snapshot.val().author,
'projectTitle': snapshot.val().projectTitle,
'text': snapshot.val().text
};
randomStore.push(doc);
console.log('randomStore length HERE is ' + randomStore.length);
});
}
Considering how the code is typed, I would assume that the 'randomStore length HERE is' log would be typed first, but instead I get this:
randomStore length is 0
randomStore length HERE is 1
randomStore length HERE is 2
randomStore length HERE is 3
If I got my data into a different array, then I could manipulate it to sort randomly and stuff like that, but I can't seem to get it in there properly.
You mentioned the timing is off? What did you mean by that ?
Have you heard of Javascript Promise's ?
http://www.html5rocks.com/en/tutorials/es6/promises/
This post explains promises very good. Read this very carefully, because if you are working with firebase, you will be using promises on daily!
Instead of using featuredRef.on("child_added") use featuredRef.once('value'). This should get you the whole array at once. Attach a then listener where you continue with the work of homeSetup.
function homeSetup() {
var cb = function(randomStore) {
console.log('randomStore length is ' + randomStore.length);
//....
};
if(ref.toString() == featuredRef.toString()){
addFeaturedImages(cb);
} /* else if(...) {
addFooImages(cb)
}*/
}
function addFeaturedImages(cb){
featuredRef.once("value", function(snapshot) {
//TODO: transform elements of the array?
cb(snapshot.val());
});
}
Code untested, but I should get you started.

Get latest record per field in Parse.com JS query

I have a table in my Parse database with columns validFrom and uniqueId. There can be multiple records with the same uniqueId (like a name)
What query do I have to use to get the items with the latest validFrom for a given set of uniqueIds? I tried the following but this limits my search to 1 item for the entire set rather than 1 item per unique_id record:
var UpdateObject = Parse.Object.extend("UpdateObject");
var query = new Parse.Query(UpdateObject);
query.containedIn("unique_id", uniqueIdsArray).select('status', 'unique_id').descending("validFrom").limit(1);
The query semantics are limited, so the only approach is to query for a superset and manipulate the result to what you need. This is better done on the server to limit the transmission of extra objects.
Big caveat: did this with pencil and paper, not a running parse.app, so it may be wrong. But the big idea is to get all of the matching objects for all of the uniqueIds, group them by uniqueId, and then for each group return the one with the maximum validFrom date...
function updateObjectsInSet(uniqueIdsArray ) {
var query = new Parse.Query("UpdateObject");
// find all of the UpdateObjects with the given ids
query.containedIn("unique_id", uniqueIdsArray);
query.limit(1000);
return query.find().then(function(allUpdates) {
// group the result by id
var byId = _.groupBy(allUpdates, function(update) { return update.get("unique_id"); });
// for each group, select the newest validFrom date
return _.map(byId, function (updates) {
_.max(updates, function(update) { return -update.get("validFrom").getTime(); });
});
});
}
To place this in the cloud, just wrap it:
Parse.Cloud.define("updateObjectsInSet", function(request, response) {
updateObjectsInSet(request.params.uniqueIdsArray).then(function(result) {
response.success(result);
}, function(error) {
response.error(error);
});
});
Then use Parse.Cloud.run() from the client to call it.

How can I delete specific rows in parse.com?

I have objects in Parse called "Post" and within that, I have columns called "title" and "content". I am trying to ask the user for an input value and save this as "remove". If the user's input value ("remove") matches a "title" value already saved in parse.com, I want to delete the entire row in parse, so that both the "title", "content" and everything else in the row is deleted. The deleting part is not working so I am wondering if my code is actually making it go through all the data saved in parse and find the one that matches the user's input and then delete it.
What am I doing incorrectly and what can I change to make it delete the entire row?
Thank you in advance.
function getPosts(){
var query = new Parse.Query(Post);
query.find({
success: function(results){
for(var i in results){
var title = results[i].get("title");
var content = results[i].get("content");
var remove = $("#post-remove").val();
console.log("Remove: "+remove);
console.log("MAC Address: " +title);
console.log("place: "+content);
if (title == remove)
{
window.alert("The MAC address matches.");
console.log(remove+" matches " + title+ " and is located in " +content);
var Post = Parse.Object.extend("Post");
var query = new Parse.Query(Post);
query.find("objectId", {
success: function(yourObj){
//console.log(yourObj);
//Post.destroy({}); //if title matches remove, delete the Post (title and content) (but it's not deleting it)
Post.remove("title");
Post.remove("content");
}
});
}
}
}
});
}
To clarify and add a bit to #JakeT's acceptable answer:
1) find objects to delete like this:
function postsMatching(title) {
var Post = Parse.Object.extend("Post");
var query = new Parse.Query(Post);
query.equalTo("title", title);
return query.find();
}
2) Delete an array of parse objects like this:
Parse.Object.destroyAll(posts);
3) Put the two ideas together (returning a promise to find then delete) like this:
var title = $("#post-remove").val();
postsMatching(title).then(function(posts) {
console.log("deleting " + JSON.stringify(posts));
Parse.Object.destroyAll(posts);
}, function(error) {
console.log("error " + JSON.stringify(error));
});
First of, you can use the Parse.Query.equalTo(key, value) method to filter for the Post/s you are looking for. That will render a lot of your logic unnecessary.
Additionally, since most parse calls are asynchronous, I would suggest learning about Parse Promises and using those instead of the call backs you're using.
Finally, you don't need a second nested query, since you already have the object you are trying to destroy. You just need to call destroy() on that object, and if you have some extra content you need to take care of deleting (i.e., your 'content' is a pointer to another object that is owned only by the Post you are deleting), you should set up a beforeDestroy() trigger for the Post object in your cloud code that will delete that pointer as well.

Categories