display specific object values in an array instead of individually? - javascript

I have used an ajax call to retrieve data from Googles places api and I have used a for/in loop to begin to pull the information. the information that I am looking for logs to the console, but I cannot get it to display in an array how I would like it to.
Right now I am getting a list of names when I request names which is a parameter in the JSON object. Is there a way to get it into an array so the I can randomly select one of the values from the array?
at this point the way it is returning my data, when I run a script to pull a random string, it pulls a random letter out of the last value to be found when searching through my JSON object.
Here is my code. Not sure if I explained myself clearly but it's the best that I could word what I am looking to do. Thanks.
// **GLOBAL VARIABLES** //
// Chosen Restaurant display area
var display = document.getElementById('chosenVenue');
// Grab button
var button = document.getElementById('selectVenue');
// Sample Array that gets queried
var venueData = ["McDonalds", "Burger King", "Wendys"];
// Grab JSON data from Google
$(document).ready(function(){
$.ajax({
url: 'hungr.php', // Send query through proxy (JSONP is disabled for Google maps)
data: { requrl: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.7484,-73.9857&radius=800&sensor=false&keyword=restaurants,food&key=AIzaSyBkCkXIHFjvqcqrRytSqD7T_RyFMNkR6bA&callback=?"}, // URL to query WITH parameters
dataType: "json",
type: "GET", // or POST if you want => update php in that case
success: function (data) {
// Traverse the array using for/in loop using i as var
for (var i in data.results) {
var results = data.results[i];
var nameResults = results.name;
console.log(nameResults);
var typesResults = results.types;
console.log(typesResults);
var vicinityResults = results.vicinity;
console.log(vicinityResults);
};
// On button click, randomly display item from selected array
button.addEventListener('click', function () {
console.log('clicked');
display.style.display = 'block';
//display.innerHTML = nameResults[Math.floor(Math.random() * nameResults.length)];
display.innerHTML = nameResults.toString() + "<br />" + vicinityResults.toString();
});
console.log('It is working');
},
error: function (request, status, error) {
console.log('It is not working');
}
});
});

Right now I am getting a list of names when I request names which is a parameter in the JSON object. Is there a way to get it into an array so the I can randomly select one of the values from the array?
Use the push method and a non-local variable:
this.nameResults = this.nameResults ? this.nameResults.push(results.name) : [];
then reference that with the Math.random method:
this.randName = function(){ return this.nameResults[Math.random() * this.nameResults.length | 0] };
References
Using Math.random flexibly
JavaScript: fast floor of numeric values using the tilde operator

Related

Create 2D Array out of another Array which is casted against an API

I'm working on a project using the opengeodata and some company-internal APIs. Therefore the code I'm using here is slightly changed.
First I'm using the Opencagedata Javascript API to get the lat/lng-Coordinates out of an address.
<script>
function geocode(query) {
$.ajax({
url: 'https://api.opencagedata.com/geocode/v1/json',
method: 'GET',
data: {
'key': 'MyKey',
'q': query,
'no_annotations': 1
},
dataType: 'json',
statusCode: {
200: function(response){ // success
var lat = response.results[0]['geometry']['lat'];
var lng = response.results[0]['geometry']['lng'];
$('#geo_result').text(lat + ' , ' + lng);
After that I'm using another internal API to get some information about places surrounding this location. Lets call them POI.
After getting those POIs I'm using splice to filter the three nearest POIs to the lat/lng Coordinates and filter on some specific keywords.
var radius = 1.5;
var POI = [];
var apiCall = $.get("CoorpAPI/" + radius + "/around/" + lat + "," + lng);
apiCall.done(function(result) {
var myLoc = result.filter(function(loc) {
return loc.id.substr(0, 3) != 'keyword';
});
$.each(myLoc, function(n, loc) {
POI.push(loc.id)
})
var top3 = POI.slice(0,3);
console.log(top3);
Now I want to run those three "top3" POIs ["AB1234", "BC2345", "CD3456"] against a second API which is returns location information.
Those information are supposed to be written into the same array into the second second dimension.
In the end I want to have something Like:
[
0: AB1234
Location Information: A
Location Information: B
1: CD2345
Location Information: C
Location Information: D
...
]
I guess the loop would have to look somewhat like this, but I'm not sure how to call the API and create a 2d-array out of the "top3" locations and the location information returned by the api:
for (var i = 0; i < top3.length; i++) {
var apiCall_2 = $.get("CoorpAPI_2"+top3[i]);
// ???
}
If I understand you correctly, you want to use a nested array inside POI to add more information after a second API call. One thing you can try is to push an array instead of just loc.id in the following manner:
POI.push([loc.id]);
Now you have a nested array in POI instead of a single string ID (I am guessing the ID is string; can be a number as well). For the second API call you can modify your code like this:
var apiCall_2 = $.get('CoorpAPI_2'+top3[i][0]);
In this way, you are using the ID which, is the first element in the nested array. Once you process all your data from API call 2, you can either push each data point separately into the nested array or, as another array like this:
// pushing each data points separately
top3[i].push(dataPoint1);
// ... up to say N data points
top3[i].push(dataPointN);
// adding as an array
top3[i].push([dataPoint1, dataPoint2, dataPointN]);
Your result will be like this:
[ ["AB1234", "dataPoint1", "dataPoint2"] ]
if you use the first approach and like this
[ [ "AB1234", ["dataPoint1", "dataPointN"] ], ]
if you use the second approach. Hope this helps.

How do I join separate json objects output from a for loop into an array?

I am scraping websites using CasperJS and one of the tasks involve crawling across url set by a for loop counter. The url looks like this
www.example.com/page/no=
where the no is any number from 0-10 set by the for loop counter. The scraper then goes through all the pages, scrapes the data into a JSON object and repeats until no=10.
The data that I am trying to get is stored in discrete groups in each page- what I would like to work with is a single JSON object by joining all the scraped output from each page.
Imagine Page1 has Expense 1 and the object I am getting is { expense1 } and Page 2 has Expense 2 and object that I am getting is { expense2 }. What I would like to have is one JSON at the end of scraping that looks like this:
scrapedData = {
"expense1": expense1,
"expense2": expense2,
}
What I am having trouble is joining all the JSON object into one array.
I initialized an empty array and then each object gets pushed to array.
I have tried a check where if iterator i in for loop is equal to 10, then the JSON object is printed out but that didnt seem to work. I looked up and it seems Object spread is an option but I am not sure how to use it this case.
Any pointers would be helpful. Should I be using any of the array functions like map?
casper.then(function(){
var url = "https:example.net/secure/SaFinShow?url=";
//We create a for loop to go open the urls
for (i=0; i<11; i++){
this.thenOpen(url+ i, function(response){
expense_amount = this.fetchText("td[headers='amount']");
Date = this.fetchText("td[headers='Date']");
Location = this.fetchText("td[headers='zipcode']");
id = this.fetchText("td[headers='id']");
singleExpense = {
"Expense_Amount": expense_amount,
"Date": Date,
"Location": Location,
"id": id
};
if (i ===10){
expenseArray.push(JSON.stringify(singleExpense, null, 2))
this.echo(expenseArray);
}
});
};
});
Taking your example and expanding on it, you should be able to do something like:
// Initialize empty object to hold all of the expenses
var scrapedData = {};
casper.then(function(){
var url = "https:example.net/secure/SaFinShow?url=";
//We create a for loop to go open the urls
for (i=0; i<11; i++){
this.thenOpen(url+ i, function(response){
expense_amount = this.fetchText("td[headers='amount']");
Date = this.fetchText("td[headers='Date']");
Location = this.fetchText("td[headers='zipcode']");
id = this.fetchText("td[headers='id']");
singleExpense = {
"Expense_Amount": expense_amount,
"Date": Date,
"Location": Location,
"id": id
};
// As we loop over each of the expenses add them to the object containing all of them
scrapedData['expense'+i] = singleExpense;
});
};
});
After this runs the scrapedData variable should be of the form:
scrapedData = {
"expense1": expense1,
"expense2": expense2
}
Updated code
One problem with the above code is that inside the for loop when you loop over the expenses, the variables should be local. The variable names also should not be Date and Location since those are built-in names in JavaScript.
// Initialize empty object to hold all of the expenses
var scrapedData = {};
casper.then(function(){
var url = "https:example.net/secure/SaFinShow?url=";
//We create a for loop to go open the urls
for (i=0; i<11; i++){
this.thenOpen(url+ i, function(response){
// Create our local variables to store data for this particular
// expense data
var expense_amount = this.fetchText("td[headers='amount']");
// Don't use `Date` it is a JS built-in name
var date = this.fetchText("td[headers='Date']");
// Don't use `Location` it is a JS built-in name
var location = this.fetchText("td[headers='zipcode']");
var id = this.fetchText("td[headers='id']");
singleExpense = {
"Expense_Amount": expense_amount,
"Date": date,
"Location": location,
"id": id
};
// As we loop over each of the expenses add them to the object containing all of them
scrapedData['expense'+i] = singleExpense;
});
};
});

How to To Delete The data in Localstorage

what I need
I need to toggle image on click.
like if user select favorite choice & then it mark unfavorite image is altered and data is deleted from localstoarge.
html code
<div style="display:block; float:right; width:auto; color:#7c7c7c;">
</div>
js code
function favaorite(sess_id,name,city,country,event_url,pointer){
var eventData;
//is anything in localstorage?
if (localStorage.getItem('eventData') === null) {
eventData = [];
} else {
// Parse the serialized data back into an array of objects
eventData = JSON.parse(localStorage.getItem('eventData'));
//alert(eventData);
$.each(eventData, function(key, value){
//console.log(value);
var imageUrl='http://im.gifbt.com/images/star1_phonehover.png';
//var imageUrl='http://im.gifbt.com/images/star1_phone.png';
$(pointer).closest('.evt_date').find('.favourate_dextop').css('background-image', 'url("' + imageUrl + '")');
//$(pointer).closest('.evt_date').find('.favourate_dextop').css('background-image', 'url("' + imageUrl + '")');
});
}
var details={};
details.sess_id=sess_id;
details.name=name;
details.city=city;
details.country=country;
details.event_url=event_url;
// Push the new data (whether it be an object or anything else) onto the array
eventData.push(details);
// Alert the array value
//alert(eventData); // Should be something like [Object array]
// Re-serialize the array back into a string and store it in localStorage
var jsondata=localStorage.setItem('eventData', JSON.stringify(eventData));
}
problem
I'm new in localstorage I need to know how could I delete data from json string.
I have implemented add to favorite now I need to mark unfavorite.
data is stored:
[{
"sess_id":182104,
"name":"AUTOMECH FORMULA",
"city":"Cairo",
"country":"Egypt",
"event_url":"automech-formula"
},]
To delete data from localstorage you use localStorage.removeItem('itemNam')
example
localStorage.setItem('name','hello');
to delete the name item from the localStorage you use
localStorage.removeItem('name');
BUT IF YOUR QUESTION IS HOW TO DELETE DATA FROM JSON OBJECT THEN YOU HAVE TWO METHODS
1: changing the original json object
delete originalJson.attributeName
originalJson = {name:'myname',age:30};//our object to test with
example :
delete originalJson.age //in this case originalJson.age is no more available
2: don't change the original object and make another copy instead
originalJson2 = JSON.stringify(originalJson);
originalJson2 = JSON.parse(originalJson2);
delete originalJson2.age //originalJson.age is available but originalJson2.age is not available
here is the : jsfiddle
let assume that sess_id is your unique id for events
function unfavorite(sess_id){
var eventData = localStorage.getItem('eventData');
//is anything in localstorage?
if (localStorage.getItem('eventData') === null) {
console.log('invalid event');
}
eventData = JSON.parse(eventData);
// Keep all without the one with specified sess_id
$.grep(eventData, function(value) {
return value.sess_id != sess_id;
});
var jsondata=localStorage.setItem('eventData', JSON.stringify(eventData));
}

retrieve unique values for key from parse.com when class has > 1000 objects

In parse I have a class named "TestScore". Each object has a key named "quizName".
I need to get an array of unique "quizName" values. I wrote the below which queries the "TestClass" and loops through the results looking for unique "quizName" values.
At first seemed to do the job. But then I realized that the maximum number of returned objects is 1000. Soon there will be more than 1000 objects stored which means that this method will not guarantee that I end up will all values.
function loadTests(){
//create an array to hold each unique test name as we find them
var uniqueEntries = [];
//query parse to return TestScore objects
var TestScore = Parse.Object.extend("TestScore");
var query = new Parse.Query(TestScore);
query.limit(1000) //added this after realizing that the default query limit is only 100
query.find({
success: function(testScore) {
$(testScore).each(function(index, score) {
//here I loop though all of the returned objects looking at the "quizName" for each
if($.inArray(score.get("quizName"), uniqueEntries) === -1) {
//if the quiz name is not already in the "uniqueEntries" array, I add it to the array
uniqueEntries.push(score.get("quizName"));
}
});
//do stuff with quiznames here...., add them as options in select boxes mostly
}
});
}
I looked at {Parse.Query} notContainedIn(key, values) which looks promising but cant figure out if I can add values to the array as I find them. It seems like I would have to have an array to start with (defeating the whole point.)
This part of the docs "{Parse.Query} Returns the query, so you can chain this call." makes me think I might be able to chain queries together to get what I need, but that doesn't seem very efficient.
How can I retrieve unique values for key "quizName" when my class has > 1000 objects?
I'm sure you're long past this by now, but only way I know of to do it is to use one query after another by using a .skip(#) value for each query. So get 1000, then query again with .skip(1000), concatenate the items from the first list and second, then query again with .skip(2000), etc...
Be aware that I think there's a limit on skip values of 10,000. Don't take my word on that, just pointing you to something that I think is right that you should confirm if you think it applies to your situation.
I eventually found a tutorial online that I was able to modify and came up with the below. This effectively sets the return limit to 10,000 instead of 1,000 and allows setting several different parameters for the query.
My changes could surely be written better, maybe as an options object or similar but it works for my needs.
You can see a working demo here
function getStuff(){
// here we will setup and call our helper functions with callbacks to handle the results
var scheme =['SOTest',true]; // return all objects with value `true` in the `SOTest` column
// var scheme =['descending','createdAt']; // return all objects with sort order applied
// var scheme =''; // or just return all objects
// see `findChunk()` below for more info
var Remark = Parse.Object.extend("Remark");
schemePromise(Remark, scheme).done(function (all) {
console.log('Found ' + all.length+' Remarks');
$.each( all, function(i, obj){
$('#test').append(obj.get('Remark') +'<br>');
});
})
.fail(function (error) {
console.log("error: " + JSON.stringify(error));
});
}
getStuff(); // call our function
// helper functions used to get around parse's 1000 query limit
// raises the limit to 10,000 by using promises
function findChunk(model, scheme, allData) {
// if `scheme` was an empty string, convert to an array
// this is the default and returns all objects in the called class
if(scheme==''){ ['scheme',''] };
// will return a promise
var limit = 1000;
var skip = allData.length;
var findPromise = $.Deferred();
var query = new Parse.Query(model);
// to get all objects from the queried Class then sort them by some column
// pass `scheme` as an array like [ sort method, column to sort ]
if (scheme[0]=='descending') query.descending(scheme[1]);
else if (scheme[0]=='ascending') query.ascending(scheme[1]);
// to limt results to objects that have a certain value in a specific column
// pass `scheme` as an array like [ column name, value ]
else query.equalTo(scheme[0], scheme[1]);
// more options can easily be built in here using `scheme`
query
.limit(limit)
.skip(skip)
.find()
.then(function (results) {
findPromise.resolve(allData.concat(results), !results.length);
}, function (results) {
findPromise.reject(error);
});
return findPromise.promise();
}
function schemePromise(model, scheme, allResults, allPromise) {
// find a scheme at a time
var promise = allPromise || $.Deferred();
findChunk(model, scheme, allResults || [])
.done(function (results, allOver) {
if (allOver) {
// we are done
promise.resolve(results);
} else {
// may be more
schemePromise(model, scheme, results, promise);
}
})
.fail(function (error) {
promise.reject(error);
});
return promise.promise();
}

How to Access Array response of AJAX

This is my AJAX call response which is in array format
[1,2,3,4,5,6]
success: function(outputfromserver) {
$.each(outputfromserver, function(index, el)
{
});
How can we access outputfromserver all values ??
Means outputfromserver Zeroth value is 1 , 2nd element is 2 , -----so on
It would help to know what your AJAX request looks like. I recommend using $.ajax() and specifying the dataType as JSON, or using $.getJSON().
Here is an example that demonstrates $.ajax() and shows you how to access the returned values in an array.
$.ajax({
url: 'test.json', // returns "[1,2,3,4,5,6]"
dataType: 'json', // jQuery will parse the response as JSON
success: function (outputfromserver) {
// outputfromserver is an array in this case
// just access it like one
alert(outputfromserver[0]); // alert the 0th value
// let's iterate through the returned values
// for loops are good for that, $.each() is fine too
// but unnecessary here
for (var i = 0; i < outputfromserver.length; i++) {
// outputfromserver[i] can be used to get each value
}
}
});
Now, if you insist on using $.each, the following will work for the success option.
success: function (outputfromserver) {
$.each(outputfromserver, function(index, el) {
// index is your 0-based array index
// el is your value
// for example
alert("element at " + index + ": " + el); // will alert each value
});
}
Feel free to ask any questions!
The array is a valid JSON string, you need to parse it using JSON parser.
success: function(outputfromserver) {
var data = JSON.parse(outputfromserver);
$.each(data, function(index, el) {
// Do your stuff
});
},
...
You can use JS objects like arrays
For example this way:
// Loop through all values in outputfromserver
for (var index in outputfromserver) {
// Show value in alert dialog:
alert( outputfromserver[index] );
}
This way you can get values at first dimension of array,
above for..loop will get values like this:
// Sample values in array, case: Indexed array
outputfromserver[0];
outputfromserver[1];
outputfromserver[2];
// So on until end of world... or end of array.. whichever comes first.
outputfromserver[...];
However, when implemented this way, by using for ( index in array ) we not only grab indexed 1,2,3,4,... keys but also values associated with named index:
// Sample values in array, case: accosiated/mixed array
outputfromserver["name"];
outputfromserver["phone"];
outputfromserver[37];
outputfromserver[37];
outputfromserver["myindex"];
// So on until end of world... or end of array.. whichever comes first.
outputfromserver[...];
In short, array can contain indexed values and/or name associated values, that does not matter, every value in array is still processed.
If you are using multidimensional stuff
then you can add nested for (...) loops or make recursive function to loop through all and every value.
Multidimensional will be something like this:
// Sample values in array, case: indexed multidimensional array
outputfromserver[0][0];
outputfromserver[0][1];
outputfromserver[1][0];
outputfromserver[1][...];
outputfromserver[...][...];
Update, JSON object:
If you server returns JSON encoded string you can convert it to javascript object this way:
try {
// Try to convert JSON string with jQuery:
serveroutputobject = $.parseJSON(outputfromserver);
} catch (e) {
// Conversion failed, result is not JSON encoded string
serveroutputobject = null;
}
// Check if object converted successfully:
if ( serveroutputobject !== null ) {
// Loop through all values in outputfromserver
for (var index in serveroutputobject) {
// Append value inside <div id="results">:
$('#results').append( serveroutputobject[index] + "<br/>" );
}
}
// In my own projects I also use this part if server can return normal text too:
// This way if server returned array we parse it and if server returns text we display it.
else {
$('#results').html( outputfromserver );
}
More information here
$.ajax({
type : "POST",
dataType: "json",
url : url,
data:dataString,
success: function(return_data,textStatus) {
temperature.innerText=return_data.temp;
// OR
**temperature.innerText=return_data['temp'];**
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error while accessing api [ "+url+"<br>"+textStatus+","+errorThrown+" ]"); return false;
}
});

Categories

Resources