Parse cloud code, access object relations - javascript

I'm trying to create a Parse cloud code function that returns the same result as a GET on parse/classes/MyClass but with the IDs of the relations.
I've done it for one object, but I can't make it work in a loop to get all the objects.
This is how I'm trying to get all the objects. It's working without the for loop and with r as a response.
Parse.Cloud.define('get_ClassName', function(request, response) {
let query = new Parse.Query('ClassName');
var ret = {};
query.find({useMasterKey: true}).then(function(results) {
for (var i = 0; i < results.length; i++) {
ret[i] = {};
const relQuery = results[i].get('status').query();
relQuery.find({useMasterKey: true}).then(function(res) {
var ids = {};
for (var j = 0; j < res.length; j++) {
ids[j] = res[j].id;
}
var status = {...status, id: ids};
status["className"] = "Status";
var r = {...r, status: status};
r["tag"] = results[i].get("tag");
ret[i] = r; //Can't access ret
//response.success(r); //Working
})
}
response.success(ret);
});
});
This is the actual result for the working version:
{
"result": {
"status": {
"id": {
"0": "xxxxxx",
"1": "xxxxxx"
},
"className": "Status"
},
"tag": "value"
}
}

response.success(ret); will run before relQuery.find finish in for loop.
Use Promise.all()
or Async await and refactor your logic.
I comment on your code about your missing.
Parse.Cloud.define('get_ClassName', function(request, response) {
let query = new Parse.Query('ClassName');
var ret = {};
query.find({useMasterKey: true}).then(function(results) { // Asyncronous
for (var i = 0; i < results.length; i++) {
ret[i] = {};
const relQuery = results[i].get('status').query();
relQuery.find({useMasterKey: true}).then(function(res) { // Asyncronous
var ids = {};
for (var j = 0; j < res.length; j++) {
ids[j] = res[j].id;
}
var status = {...status, id: ids};
status["className"] = "Status";
var r = {...r, status: status};
r["tag"] = results[i].get("tag");
ret[i] = r; //Can't access ret
//response.success(r); //Working
console.log(`index {i}`, r);
})
}
console.log(`response will be called`);
response.success(ret); // Called before `relQuery.find` finish
});
});

Related

How to change csv to json array using javascript

I want to add an external CSV file into a JOSN Array in my JS Code.
I tried lots of codes, with no luck like this:
var map = {};
var rows = csv.split(/\n/g);
var keys = rows.shift().split(",");
rows.forEach(raw_row => {
var row = {};
var row_key;
var columns = raw_row.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);
columns.forEach((column, index) => {
var key = keys[index];
if (!key) return;
if (key === 'Name') {
row_key = column;
return;
}
if (key === "Coordinates") {
column = column.replace(/""/g, '"');
column = column.substring(1, column.length - 1);
column = column.replace(/([a-zA-Z_]+):/g, `"$1":`);
try {
column = JSON.parse(`{${column}}`);
} catch (e) {}
}
row[key] = column;
});
map[row_key] = row;
});
console.log(map);
but I believe my expectation is something else, so I dont get what I want.
could some one pleae help me to change this csv(file):
contry;fromNr;toNr;Type;cust_1;cust_2
US;0;100;wood;max;nuk
DE;100;500;metal;max;pal
into JSON Array:
[{
"country": "US",
"fromNr": 0,
"toNr": 100,
"Type": "wood",
"cust_1": "max",
"cust_2": "nuk"
}, {
"country": "DE",
"fromNr": 100,
"toNr": 500,
"Type": "metal",
"cust_1": "max"
}]
You can use the below function csvIntoJson to convert.
const csv = 'contry;fromNr;toNr;Type;cust_1;cust_2\nUS;0;100;wood;max;nuk\nDE;100;500;metal;max;pal';
const csvIntoJson = (csv, separator) => {
let [headers, ...rows] = csv.split('\n');
headers = headers.split(separator);
rows = rows.map(row => row.split(separator));
return rows.reduce((jsonArray, row) => {
const item = row.reduce((item, value, index) => {
return {...item, [headers[index]]: value};
}, {});
return jsonArray.concat(item);
}, []);
};
const jsonArray = csvIntoJson(csv, ';');
My suggestion use a library, But you still want to understand how it can be done then here is the simple code.
I have used ',' delimiter, You can change it to ';' or anything else as per your usecase.
steps:
Read csv as text
split text by new line to get rows
split row by delimiter like ',' or ';'
Do your stuff
code:
function Upload(input){
console.log("uploading");
let file = input.files[0];
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function() {
map_object = [];
console.log(reader.result);
var textByLine = (reader.result).split("\n")
console.log(textByLine);
// read header
header = (textByLine[0]).split(',');
// read data
for(var i = 1 ; i< textByLine.length -1; i++){
temp_row = {}
row_data = textByLine[i].split(',');
for (var j = 0 ; j< header.length; j++){
temp_row[header[j]] = row_data[j]
}
console.log(temp_row);
map_object.push(temp_row);
}
console.log(map_object);
document.write(JSON.stringify(map_object));
};
reader.onerror = function() {
console.log(reader.error);
};
}
<input type="file" id="fileUpload" accept='.csv' onchange="Upload(this)"/>
var data = "contry;fromNr;toNr;Type;cust_1;cust_2\nUS;0;100;wood;max;nuk\nDE;100;500;metal;max;pal";
function CSVtoJSON(csv) {
var lines = csv.split("\n");
var result = [];
var headers = lines[0].split(";");
for (var i = 1; i < lines.length; i++) {
var obj = {};
var currentline = lines[i].split(";");
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
return result;
}
console.log(CSVtoJSON(data));

How can I map this asynchronous NPM twit function onto an array?

I'm trying to figure out how to map this async function onto an array that I am using. The code that I tried is returned undefined since the promise isn't completing.
I am using NPM twit and this is the function that is supposed to return a number when an ID is passed into it
ids = ['1084212656771350532','2450457644','1244639845743570948','1081269935031140353','1227966230511980550','752215003143430145']
T.get('statuses/user_timeline', { user_id: id, count: 100, exclude_replies: true, include_rts: false }, function (err, data, response) {
if (err) {
console.log('err');
} else {
var rtTotal = 0;
var likeTotal = 0;
for (var i = 0; i < data.length; i++) {
rtTotal += data[i].retweet_count;
var rtAverage = rtTotal / data.length;
}
for (var i = 0; i < data.length; i++) {
likeTotal += data[i].favorite_count;
var likeAverage = likeTotal / data.length;
}
}
var influenceScore = (.33 * rtAverage) + (.2 * likeAverage) + (.33 * (data[0].user.followers_count)) + (.14 * (data[0].user.statuses_count));
console.log(influenceScore);
return influenceScore;
})
For example the result should be an array with numerical values
[1123.11, 9200, 21882, 1011, 23110.22]

Issues getting data from array's dictionary JS

I'm having issues to get the stored data in my array. I can't see where is the problem on my function and why is returning undefined elements.
This is the function where I store data in the array:
function getTaskKidData(str) {
var tasks = $('#tasks_data > div');;
var formated_tasks = [];
var formated_kids = [];
formated_homeworks = [];
tasks.each(function(index) {
var task_kids = $(this).find('ul').eq(0).find('li');
var task_homeworks = $(this).find('ul').eq(1).find('li');
if (task_kids.length > 0 && task_homeworks.length > 0) {
task_kids.each(function(index) {
var kid_name = $(this).text().trim();
if (str == "kid"){
var kid = $('#kid_list > li > a[class*="active"]').text().replace(window.location.pathname.split('/')[2],'').trim();
if (kid == kid_name){
formated_kids.push({'name': kid_name});
}
}else{
formated_kids.push({'name': kid_name});
}
});
task_homeworks.each(function(index) {
var homework_name = $(this).find('p').eq(0).text().trim();
var homework_date = $(this).find('p').eq(1).text().trim();
formated_homeworks.push({
'name': homework_name,
'date': homework_date,
});
});
formated_tasks.push({
'kids': task_kids,
'homeworks': task_homeworks,
})
}
});
return formated_tasks;
}
I don't understand why the objects in the output of the array are "li" tags if I'm storing data as text. The output of the array is the next one:
This is the code where I'm trying to get the data:
var tasks = getTaskKidData("kid");
console.log(tasks)
for (let i = 0; i < tasks.length; i++) {
console.log("schedule");
for (let j = 0; j < tasks[i]['kids'].length; j++) {
console.log(tasks[i]['kids'][j]['name']);
}
for (let j = 0; j < tasks[i]['homeworks'].length; j++) {
console.log(tasks[i]['homeworks'][j]['name']);
console.log(tasks[i]['homeworks'][j]['date']);
}
}
And this is the output when I run the code:
Any idea of the problem?
Thanks for reading!!
In your code you have
var task_kids = $(this).find('ul').eq(0).find('li');
and later you log task_kids. The log output shows li elements because that was what you selected.

How to resolve something.something programmatically

I have following code:
;(function($){
var getWeatherInfo = function(url, requiredKeys ) {
var info = {},
dfd = $.Deferred();
$.getJSON( url, function( data ) {
for(var i = 0; i < requiredKeys.length; i++) {
info[requiredKeys[i]] = data[requiredKeys[i]];
}
dfd.resolve(info);
});
return dfd.promise();
};
var url = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk',
requiredData = [
'name',
'coord.lat',
'coord.lon',
'description'
];
getWeatherInfo(url,requiredData).done(function(data){console.log(data)});
The data output is:
Object {name: "London", coord.lat: undefined, coord.lon: undefined, description: undefined}
Name is working fine because it doesn't have . How can I fix rest? I don't want to use eval. Is there any better alternative?
This will work:
$.getJSON( url, function( data ) {
for(var i = 0; i < requiredKeys.length; i++) {
if (requiredKeys[i].indexOf('.') > -1){
var ar = requiredKeys[i].split("\.");
info[requiredKeys[i]] = data[ar[0]][ar[1]]
}
else{
info[requiredKeys[i]] = data[requiredKeys[i]];
}
}
dfd.resolve(info);
});
Result: Object {name: "London", coord.lat: 51.51, coord.lon: -0.13, description: undefined}
http://jsfiddle.net/gpzd9w43/
EDIT:
Maybe a more elegant way to do it if you have more than 1 dot:
$.getJSON( url, function( data ) {
for(var i = 0; i < requiredKeys.length; i++) {
var ar = requiredKeys[i].split("\.");
var node = data;
for (var j = 0; j < ar.length; j++){
node = node[ar[j]];
}
info[requiredKeys[i]] = node;
}
dfd.resolve(info);
});
http://jsfiddle.net/gpzd9w43/1/

Issue to Get data from two dimentional json

i have a nested json which give me error.
JSON:
[{"id":"15",
"rand_key":"",
"landlord_name":"Shah",
"property_req_1":{
"lead_req_id":"",
"lead_id":"0",
"category_id":"1",
"region_id":"1",
"area_location_id":"17",
"sub_area_location_id":"3447",
"min_beds":"1",
"max_beds":"",
"min_budget":"3332",
"max_budget":"0",
"min_area":"",
"max_area":"0",
"unit_type":"2",
"unit_no":"",
"listing_id_1_ref":"RH-R-17",
"listing_id_1":"17"
}
}]
Code:
var json=null;
$.getJSON("ajax_files/getSingleRow_leads.php?id="+id, function(json){
json = json[0];
here alert(json.property_req_1); give me [object Object]
if(json.property_req_1){
var getReq = jQuery.parseJSON('['+json.property_req_1+']');
$.each(getReq, function(id, key) {
can not get it here
});
}
});
what i am missing?
for (var i = 0; i < json.length; i++) {
var firstData = json[i];
for (var j = 0; j < json.property_req_1.length; j++) {
var data = json.property_req_1[j];
}
}

Categories