I have a function that receives data from a previous JSON response, calls another web service, and adds the results from the second call to the end of the original JSON response. However, the items in my original array get replaced by items in the new array when I used extend. I understand that using $.extend will override my items with identical keys, but I cannot find another option as I am not trying to $.merge my items as I need to concatenate them. Is there any other viable option? Thanks!
//data is the object to which I am trying to add data
function verificaFileServer(data, subprograma, etapa, destino, lista, listaFileServer){
//checking whether some variable has been passed into the function
if(listaFileServer !== undefined){
//SharePoint REST Endpoint
var urlREST = "/_api/lists/getbytitle('File Server')/items?" +
"$select=Title,Link,Modified&$orderby=Modified desc&$filter=IDdoEvento eq " + subprograma + " and EtapaPAS eq '" + etapa + "' and TipodeArquivo eq '" + listaFileServer + "'";
$.ajax({
url: urlREST,
headers: { "Accept": "application/json; odata=verbose"},
success:function(dadosFileServer) {
//trying to add to the end of my original JSON object
$.extend(data.d.results,dadosFileServer.d.results);
//creating a new array containing the original and the new data
dadosConcatenados = data.d.results.sort(function(a, b) {
return (b["Modified"] > a["Modified"]) ? 1 : ((b["Modified"] < a["Modified"]) ? -1 : 0);
});
//calling a function that will build the output based on the concatenated array
montaSaida(dadosConcatenados, subprograma, etapa, lista, destino);
}
});
} else {
//calling a function that will build the output based on the original data
montaSaida(data, subprograma, etapa, lista, destino);
}
}
However, the items on the original array get replaced by items in the
new array.
Try using Array.prototype.concat()
var data = [1, 2, 3];
data = data.concat(4, 5, 6, 7, {"abc": [8, 9]});
console.log(data)
Related
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.
First thing, the simple response which I get back from $.ajax is this:
http://pastebin.com/eEE72ySk
I am using this code:
$.ajax({
url: "/api/Flight/SearchFlight",
type: "Post",
data: $('form').serialize() + '&' + $.param({
'TokenId': $("#pageInitCounter").val()
}, true),
success: function(data) {
var result = JSON.parse(data);
$('#responsestatus').text(result.Response.ResponseStatus);
});
I was trying this code:
$.each(result.Response.Results[0][0].AirlineRemark, function (i, item) {
$("#divResult1").append('<p>' + item.AirlineRemark + '</p>');
});
When I use the above code, then error is:
Uncaught TypeError: Cannot use 'in' operator to search for '5' in IndiGo
When I tried this code without the forEach loop :
$("#divResult1").text(result.Response.Results[0][0].AirlineRemark);
I get no error but the output is only the first one. Indigo is showing however in response there are 20 arrays in Results. I have shown only two arrays in result in the link provided above.
Please someone tell me how to iterate each and every item in results array.
AirlineRemark is not an Array, so looping through that one is not possible. So loop through the array of arrays, and find the property within each loop
$.each(result.Response.Results[0], function (i, item) {
$("#divResult1").append('<p>' + item.AirlineRemark + '</p>');
});
You're trying to iterate a non-array there. If, result is based on your JSON that you provided. This is one way you can iterate it,
// Each items in result.Response.Results
$.each(result.Response.Results, function(i, items) {
// Get the AirlineRemark at the item at 0 index.
var airlineRemark = items[0].AirlineRemark;
// Append it to #divResult1
$("#divResult1").append('<p>' + airlineRemark + '</p>');
});
Beware that on sample above, items is an array. And it will only get the first item.
You can try this
$.each(result.Response.Results, function () {
$("#divResult1").append('<p>'+this[0].AirlineRemark+'</p>');
});
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));
}
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
I'm new to jQuery. Following is the data variable that contains a json dictionary.
{
"user":null,
"currency":"EUR",
"balance":0,
"translist": [
{ "trans1":"something","trans2":"something2" }
]
}
and my jQuery method receives a json/Javascript object from the Rest GET call
success: function (data){
for(x in data) {
console.log(x + ': ' + data[x]);
}
});
Is there any library that can help to parse/walk through this json object and get to some kind of objects list? I want to check some of the keys and their respective values. Problem is I don't need all the keys and values from the list and also some of the values can be null, which prevented me to apply some solutions I found using SO.
Or usually is it more common to directly start printing the HTML inside the success function?
EDIT:If it was java for example it would be a Map and I would use an iterator to walk through and see/analyse the map values, and create some array list with the values I want from it. What's equivalent of that in jQuery?
If it was java for example it would be a Map and I would use an
iterator to walk through and see/analyse the map values, and create
some arraylist with the values I want in it. What is the equivalent of that
in jQuery?
Any javascript object can be seen as an associative map.
You can for example directly access the currency as data['currency'].
You can also build an array :
var a = [];
for (var key in data) {
a.push({key:key, value:data[key]});
}
You could also build some HTML and apply functions to the data :
$(document.body).append($(
'<table>' + a.map(function(v){
return '<tr><td>'+v.key+'</td><td>'+v.value+'</td></tr>'
}).join('')+'</table>'
));
Demonstration
Using jQuery can make the same iteration simpler (working directly from data) :
$(document.body).append($(
'<table>' + $.map(data, function(value,key){
return '<tr><td>'+key+'</td><td>'+value+'</td></tr>'
}).join('')+'</table>'
));
Demonstration
Try using each
success: function (data){
$.each( data, function( key, value ) {
if(key === "currency")
alert( key + ": " + value );
});
});