Issue to Get data from two dimentional json - javascript

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];
}
}

Related

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.

Parse cloud code, access object relations

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
});
});

how to form json structure in javascript

All, I have a module to import CSV file and fetch data and display in a grid. Fetched the data in array but I expected value must be in a particular JavaScript data structure.
Here my sample code
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
console.log("headers-->"+headers)
var lines = [];
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j=0; j<headers.length; j++) {
tarr.push(headers[j]+":"+data[j]);
}
lines.push(tarr);
// console.log(lines)
}
}
console.log("details ="+lines)
});
allText Value
serial,Asset Type,id
Asset1,Equipemnt,id1
Asset2,Equipemnt,id2
Asset3,Equipemnt,id3
Asset4,Equipemnt,id4
My output:
Serial:Asset1,Asset Type:Equipment,id:RF0001,
Serial:Asset2,Asset Type:Equipment,id:R0002,
Serial:Asset3,Asset Type:Equipment,id:R0003,
Serial:Asset4,Asset Type:Equipment,id:F0004,
Serial:Asset5,Asset Type:Equipment,id:F0005,
Serial:Asset6,Asset Type:Equipment,id:0006,
Serial:Asset7,Asset Type:Equipment,id:007,
Expected structure:
{
serial:["Asset1","Asset1","Asset2","Asset3","Asset4"],
Asset Type:["Equipment","Equipment","Equipment","Equipment","Equipment"],
id:["id1","id2","id3","id4",]
}
How to achieve this structure?
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
console.log("headers-->"+headers)
//initializing resulting json
var lines = {};
//initializing arrays for all the headers
for(var i=0; i<headers.length; i++){
lines[headers[i]] = [];
}
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
for (var j=0; j<headers.length; j++) {
lines[headers[j]].push(data[j]);
}
}
}
return lines
}
//format all text is taken up (I tested on a string)
allText = "serial,Asset Type,id\n Asset1,Equipemnt,id1\nAsset2,Equipemnt,id2\nAsset3,Equipemnt,id3\nAsset4,Equipemnt,id4"
Result :
You first line is header and wanted to set as a key object . So you already get that var headers = allTextLines[0].split(','); thus assign that object key by object[key] = value format .
I assume that your header and lines splited key has the same thus I loop allTextLines and used the same key for both headers and allTextLines !!
var all = "serial,Asset Type,id \n"+
"Asset1,Equipemnt,id1 \n"+
"Asset2,Equipemnt,id2 \n"+
"Asset3,Equipemnt,id3 \n"+
"Asset4,Equipemnt,id4";
processData(all);
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = {};
//set headers as key
for(var i = 0 ; i < headers.length;i++) {
lines[headers[i]] = [];
}
//assign relative value to key
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
for(var d in data) {
lines[headers[d]].push(data[d]);
}
}
console.log(lines)
}

TypeError: Cannot find function getFrom in object GmailMessage

I have the following function in Google Apps Script:
function getMail() {
var threads = GmailApp.getInboxThreads(0, 50);
var messages = GmailApp.getMessagesForThreads(threads);
var froms = [];
for (var i=0; i<messages.length; i++) {
var msg = messages[i];
Logger.log(msg.getFrom());
}
}
getMessagesForThreads returns a list of GmailMessage objects.
So why can't it access the getFrom method?
function getMail() {
var threads = GmailApp.getInboxThreads(0, 50);
var messages = GmailApp.getMessagesForThreads(threads);
for (var i=0; i<messages.length; i++) {
for (var j=0; j<messages[i].length; j++) {
Logger.log(messages[i][j].getFrom());
}
}
}
getMessagesForThreads returns GmailMessage[][] not a GmailMessage[] like I had thought.

Multidimentioanal arrays in JavaScript values not appending

I am trying to add values in a multidimensional array in JavaScript, but it doesn't seem to work. I get "variable not defined" error in snippet but can't see any variable which is not defined.
Does anyone have any idea what's going wrong here?
Many Thanks,
Hassam
var abc = "11:00, 11:10, 12:20,12:30";
var split = abc.split(",")
var limits = new Array();
var alltimes = [[],[]];
//var split = ["11:00", "11:10", "12:20","12:30"];
var x = 0;
for (var i = 0; i < split.length -1 ; i++) {
limits.push(split[i]);
// alert(split.length );
if(i%2 === 1) // If odd value
{
alert(limits);
for (var j = 0;j<2; j++)
{
// alert(limits[j]);
alltimes[x][j] = limits[j];
}
limits.length = 0;
x++;
}
// alert(split.length + 2);
//
}
alert(alltimes);
// console.log(abc)
This is my JavaScript code
$(document).ready(function(){
$('.timepicker').click(function(){
var ajaxurl = 'Ajax.php',
data = {'action': 'Hassam'};
$.post(ajaxurl, data, function (response) {
// $('#timepicker').timepicker('option', 'disableTimeRanges', [abc]);
var split = response.split(",");
var x = 0;
for (var i = 0; i < split.length -1 ; i++) {
limits.push(split[i]);
alert(split.length );
if(i%2 === 1) // If odd value
{
for (var j = 0;j<2; j++)
{
// alert(limits[j]);
alltimes[x][j] = limits[j];
}
limits.length = 0;
x++;
}
alert(split.length + 2);
//
}
alert(alltimes);
// console.log(abc)
});
There is very simple solution to achieve what you want.
var split = ["11:00", "11:10", "12:20", "12:30"];
var alltimes = [];
while (split.length) {
alltimes.push(split.splice(0, 2));
}
console.log(alltimes);

Categories