jQuery filter result - javascript

I need your help. I get hash tags data from Tumblr via ajax and I loop through them to output them. Before I output the tags I want to do some filtering, and in the output if I have 4 of the same hash tag I need to only output it once.
Here is an example where without the filtering.
jsFiddle
$.ajax({
url: "http://api.tumblr.com/v2/blog/testhermes.tumblr.com/posts",
dataType: 'jsonp',
data: {
api_key : "d01TZzpbq12cD7Zv7dM4EwLndkAAIEsExnLl9PNvsHYuyuDwKq"
},
success: function(results){
var posts = results.response.posts;
var text ='';
for (var i in posts)
{
p = posts[i];
a = p.tags;
for(var j in a) {
c = a[j];
text += ''+ c +'<br>';
$("body").append(text);
}
}
}
});
thank you

You just have to hold value in array and check every time you insert item whether it exist in array or not.
$.ajax({
url: "http://api.tumblr.com/v2/blog/testhermes.tumblr.com/posts",
dataType: 'jsonp',
data: {
api_key : "d01TZzpbq12cD7Zv7dM4EwLndkAAIEsExnLl9PNvsHYuyuDwKq"
},
success: function(results){
var posts = results.response.posts;
var text ='';
var arr = [];
for (var i in posts)
{
p = posts[i];
a = p.tags;
for(var j in a) {
c = $.trim(a[j]);
if(jQuery.inArray(c, arr) == -1)
{
arr.push(c);
var text = ''+ c +'<br>';
$("body").append(text);
}
}
}
}
});
Here is JS FIDDLE link.

Simply keep track of tags you've already seen in an object, then only output the link if you haven't seen the tag before.
var seen_tags = {};
for (var i in posts)
{
p = posts[i];
a = p.tags;
for(var j in a) {
c = a[j];
if(!(c in seen_tags)) {
text += ''+ c +'<br>';
$("body").append(text);
seen_tags[c] = true;
}
}
}

Related

Filter looped json to only return variable match results

I am trying to loop over my json results to output only the matches of _miner. Currently the console only outputs "[]" and the html is blank. I can't seem to figure out which part of the grep or for loop needs to be modified to have this return correctly.
Json Sample:
{
"zelcash-114746": "0000000b195cc1419217007c01efcf1b6d90f16a215779b33b4ae06096b33b3d:942b928560a8e6231b0ee1e0a3db7b3ff67b4e5251de1880fe1830c418a3475d:114746:t1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU.Home:1531052142518",
"zelcash-114481": "00000003ffbbcfde0b28f7f714909e18cd09de9c314207588a6e55a217a73c05:fbd33717c50b67fc3e84d94b46d758a464e81d0c8546ed5a887a046e495cee07:114481:t1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU.Lana:1531019942228",
"zelcash-114423": "000000055a78937228c6a1f40e18c8553fab30e1f5ce84ff1fe47e27425d88fc:02043e03a090d31227e44dcabb03d4977d835531733c1684ec8112898b02f22a:114423:t1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU.Del:1531013991740",
"zelcash-113970": "00000000838236ceb41b564f076b813b55afaebca93cda1b289e3698f84f5f2e:8176a2ae4077c08952b3802a18ee70a69d5407b1dcb090c6631dbb9ba709d1a7:113970:t1UWajgJUBdmzwgDvy9D2gyhHGq6dimbW2a.10603g1:1530959630994"
}
HTML
<p id="demo"></p>
JS/Ajax
$.ajax({
url: "https://xxxxx/api/blocks",
dataType: 'json',
success: function (data) {
var _miner='t1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU';
// find object
for (var x in data) {
var blockfound = $.grep(data, function(n,i) {
return n.x == _miner
});
document.getElementById("demo").innerHTML += blockfound + "<br>";
}
console.log(blockfound);
},
error: function() {
//alert("Was unable to get info!");
}
});
use for in to lopp through the data and use .includes() to find the values that contains the _miner :
const data = {
"zelcash-114746": "0000000b195cc1419217007c01efcf1b6d90f16a215779b33b4ae06096b33b3d:942b928560a8e6231b0ee1e0a3db7b3ff67b4e5251de1880fe1830c418a3475d:114746:t1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU.Home:1531052142518",
"zelcash-114481": "00000003ffbbcfde0b28f7f714909e18cd09de9c314207588a6e55a217a73c05:fbd33717c50b67fc3e84d94b46d758a464e81d0c8546ed5a887a046e495cee07:114481:t1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU.Lana:1531019942228",
"zelcash-114423": "000000055a78937228c6a1f40e18c8553fab30e1f5ce84ff1fe47e27425d88fc:02043e03a090d31227e44dcabb03d4977d835531733c1684ec8112898b02f22a:114423:t1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU.Del:1531013991740",
"zelcash-113970": "00000000838236ceb41b564f076b813b55afaebca93cda1b289e3698f84f5f2e:8176a2ae4077c08952b3802a18ee70a69d5407b1dcb090c6631dbb9ba709d1a7:113970:t1UWajgJUBdmzwgDvy9D2gyhHGq6dimbW2a.10603g1:1530959630994"
}
const _miner = 't1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU',
result = [];
for (let i in data) {
if (data[i].includes(_miner))
result.push({
[i]: data[i]
})
}
result.forEach(e => {
document.querySelector('#demo').innerHTML += Object.values(e)[0] + '<br />';
})
<p id="demo"></p>
your code should be like :
$.ajax({
url: "https://xxxxx/api/blocks",
dataType: 'json',
success: function(data) {
var _miner = 't1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU', result = [];
// find object
for (let i in data) {
if (data[i].includes(_miner))
result.push({
[i]: data[i]
})
}
document.getElementById("demo").innerHTML += result + "<br>";
console.log(result);
},
error: function() {
//alert("Was unable to get info!");
}
});
However , document.getElementById("demo").innerHTML += result + "<br>"; might not work as expected, either use a loop to display the result ( like in the snippet above )
in case you want to keep $.grep, you'll nee do pass an array of values to it instead of an object and use includes like :
var blockfound = $.grep(Object.values(data), function(n,i) {
return n.includes(_miner)
});
console.log(blockfound)
You need to get the value from the data hash first, then you need to parse it to get the miner field (it can be done using regex).
var _miner='t1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU';
var success = function (data) {
var blockfound = [];
var x;
for(x in data) {
var content = data[x];
var s = content.match(/^([a-f0-9]+):([a-f0-9]+):(\d+):([A-Za-z0-9_-]+)\.([A-Za-z0-9]+):(\d+)$/);
if (s && s[4]===_miner){
document.getElementById("demo").innerHTML += content + "<br>";
blockfound.push(content);
}
}
console.log(blockfound);
}
success({
"zelcash-114746": "0000000b195cc1419217007c01efcf1b6d90f16a215779b33b4ae06096b33b3d:942b928560a8e6231b0ee1e0a3db7b3ff67b4e5251de1880fe1830c418a3475d:114746:t1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU.Home:1531052142518",
"zelcash-114481": "00000003ffbbcfde0b28f7f714909e18cd09de9c314207588a6e55a217a73c05:fbd33717c50b67fc3e84d94b46d758a464e81d0c8546ed5a887a046e495cee07:114481:t1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU.Lana:1531019942228",
"zelcash-114423": "000000055a78937228c6a1f40e18c8553fab30e1f5ce84ff1fe47e27425d88fc:02043e03a090d31227e44dcabb03d4977d835531733c1684ec8112898b02f22a:114423:t1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU.Del:1531013991740",
"zelcash-113970": "00000000838236ceb41b564f076b813b55afaebca93cda1b289e3698f84f5f2e:8176a2ae4077c08952b3802a18ee70a69d5407b1dcb090c6631dbb9ba709d1a7:113970:t1UWajgJUBdmzwgDvy9D2gyhHGq6dimbW2a.10603g1:1530959630994"
});
<p id="demo"></p>

jQuery - how to receive result from an inner ajax call?

I am developing an web app in which the user will be able to identify the location from map by clicking on the map (I use jquery 3.1). The problem is that I have to make some ajax calls, one depend on other, and on the last call the result it's not returned as a whole (full array) and I received only a part of array.
The problem survives from var a4.
How I can make that a4 result to be send as a full array because I tried with deferred but with no expecting result?
var getLocDetails = function () {
// Parse a web api based on user lat & lon
var a1 = $.ajax({
method: 'GET',
url: 'http://nominatim.openstreetmap.org/reverse?lat=44.43588&lon=26.04745&accept-language=ro&format=json'
});
// Get osm_type & osm_id and parse another web service to get a XML document (Ex.: https://www.openstreetmap.org/api/0.6/way/28240583)
var a2 = a1.then(function (data) {
return $.ajax({
method: 'GET',
url: 'https://www.openstreetmap.org/api/0.6/' + data.osm_type + '/' + data.osm_id
})
});
// Get all 'ref' attribute from every 'nd' node from XML and make an array with this values
var a3 = a2.then(function (data) {
var osmChildren = data.documentElement.childNodes;
var out = [];
for (var i = 0; i < osmChildren.length; i++) {
if (osmChildren[i].nodeName == 'way') {
var wayChildren = osmChildren[i].childNodes;
for (var j = 0; j < wayChildren.length; j++) {
if (wayChildren[j].nodeName == 'nd') {
var ndRef = Number.parseInt(wayChildren[j].getAttribute('ref'));
out.push(ndRef);
}
}
}
}
return out;
});
// HERE IS THE PROBLEM
// Based on array returned from a3, I am parsing every link like 'https://www.openstreetmap.org/api/0.6/node/ + nodeRef' to extract every lat and lon values for extreme points
var a4 = a3.then(function (data) {
var defer = $.Deferred();
var out = [];
for (var i = 0; i < data.length; i++) {
var nodeRef = data[i];
var nodeUrl = 'https://www.openstreetmap.org/api/0.6/node/' + nodeRef;
$.ajax({
method: 'GET',
url: nodeUrl
}).done(function (response) {
var node = response.documentElement.firstElementChild;
var lat = Number.parseFloat(node.getAttribute('lat'));
var lng = Number.parseFloat(node.getAttribute('lon'));
out.push([lat, lng]);
defer.resolve(out);
});
}
return defer.promise();
});
// When a4 is done, based his result, I have to have an array of lat & lon coordonates, but I recived only 1-2 coordonates even I have 10.
a4.done(function (data) {
console.log(data);
// Here I have to draw a polygon
});
}
you need to handle the requests in an array, as what you are doing tends to resolve the callback for a4 before all are complete.
To do this we can use $.when function
var req = [];
// Based on array returned from a3, I am parsing every link like 'https://www.openstreetmap.org/api/0.6/node/ + nodeRef' to extract every lat and lon values for extreme points
var a4 = a3.then(function (data) {
var defer = $.Deferred();
var out = [];
for (var i = 0; i < data.length; i++) {
var nodeRef = data[i];
var nodeUrl = 'https://www.openstreetmap.org/api/0.6/node/' + nodeRef;
req.push(
$.ajax({
method: 'GET',
url: nodeUrl
}).done(function (response) {
var node = response.documentElement.firstElementChild;
var lat = Number.parseFloat(node.getAttribute('lat'));
var lng = Number.parseFloat(node.getAttribute('lon'));
out.push([lat, lng]);
})
);
}
$.when.apply($, req).done(function(){
return defer.resolve(out);
});
return defer.promise();
});

Pulling a Usable Link out of a JSON Object

I need to figure out how to have a link that I pull from a JSON object an ACTUAL link that the user can click and follow to the site instead of just text. I feel like it's gotta be a quick fix, but I can't seem to figure it out! Thanks for the help!!
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function(response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $("<a href='deals[i].deal.untracked_url'>" + deals[i].deal.untracked_url + "</a>");
couponInfo.append(newUntrackedURL)
}
})
};
Assuming your fetched data is correctly used, here's why your link doesn't work : the href is actually deals[i].deal.untracked_url instead of its content.
try this instead :
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function (response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $('' + deals[i].deal.untracked_url + "");
couponInfo.append(newUntrackedURL)
}
})
};
Without the generated JSON, I can't help you further if this solution doesn't helps.
Look like maybe you had a typo:
'deals[i].deal.untracked_url' should be 'deals["+ i +"].deal.untracked_url'
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function (response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $("<a href='deals["+ i +"].deal.untracked_url'>" +
deals[i].deal.untracked_url + "</a>");
couponInfo.append(newUntrackedURL)
}
});
Scratch that - you want it to pull the value not write out "deals[i].deal.untracked_url." To do that you do the below.
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function (response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $("<a href='"+deals[i].deal.untracked_url+"'>" +
deals[i].deal.untracked_url + "</a>");
couponInfo.append(newUntrackedURL)
}
});

Replace string in text area with the value of ajax response

I have an ajax function that returns a shorturl of an url from a textarea.
When I want to replace the shorturl by the actual url in the text area by using replace, the code not work. this is my implementation
Ajax function:
function checkUrl(text) {
var bit_url = "";
var url = text;
var username = "o_1i42ajamkg"; // bit.ly username
var key = "R_359b9c5990a7488ba5e2b0ed541db820";
return $.ajax({
url: "http://api.bit.ly/v3/shorten",
data: {
longUrl: url,
apiKey: key,
login: username
},
dataType: "jsonp",
async: false,
success: function(v) {
bit_url = v.data.url;
}
});
}
and a function that call the checkurl function is implemented as follow
$("#urlr").change(function() {
var text = $("#Pushtype_message").val();
var c = "";
var msgtext = "";
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var MsgStr = $("#Pushtype_message").val();
var Arr = text.split(" ");
urllist = new Array();
urluri = new Array();
i = 0;
for (var n = 0; n < Arr.length; n++) {
txtStr = Arr[n];
var urltest = urlRegex.test(txtStr);
if (urltest) {
urllist[i] = txtStr;
}
}
for (var i = 0; i < urllist.length; i++) {
// console.log(urllist[i].toString());
checkUrl(urllist[i]).done(function(result) {
var response = (result.data.url);
console.log(response);
MsgStr.replace(urllist[i], response);
console.log(MsgStr);
$("#Pushtype_message").val(MsgStr);
});
}
});
In my text area I put this text:
test utl function https://www.google.Fr test success
and I get in my console the following result
main.js http://bit.****
main.js test utl function https://www.google.Fr test success
As you see, the function return an urlshortner but the initial text still the same. My expected result is: test utl function http://bit.l**** test success, but this don't work.
When working with textarea you can simply replace their text.
$("#Pushtype_message").text(MsgStr);
You need the assign the new value to MsgStr
for(var i=0; i<urllist.length; i++){
// console.log(urllist[i].toString());
checkUrl(urllist[i]).done(function(result){
var response=(result.data.url);
console.log(response);
MsgStr = MsgStr.replace(urllist[i],response);
console.log(MsgStr);
$("#Pushtype_message").val(MsgStr);
});
}
i is defined outside your for loop and used inside it urllist[i]=txtStr; but its value is never assigned, it's alaways = 0:
i=0;
for (var n = 0; n < Arr.length; n++) {
txtStr = Arr[n];
var urltest=urlRegex.test(txtStr);
if(urltest)
{
urllist[i]=txtStr;
}
}
I found the solution about my problem,
I affect urllist[j] to a new variable text, because in the checklist function urllist[j] return an undefined value.
var j=0;
for(j; j<urllist.length; j++){
var text=urllist[j];
checkUrl(urllist[j]).done(function(result){
var response=result.data.url;
console.log(urllist[j]);
MsgStr1 = MsgStr.replace(text,response);
console.log(MsgStr1);
$("#Pushtype_message").val(MsgStr1);
});
}
});

Uncaught TypeError: Cannot read property 'HotelInfo' of undefined

//an ajax call to the api
jQuery(document).ready(function() {
jQuery.ajax({
url:"http://localhost:8080/activitiesWithRealData?location=%22SEA%22&startDate=%2205-14-16%22&endDate=%2205-16-16%22&theme=%22food%22",
dataType: 'JSON', type: 'GET',
success: function (data)
var viewModel;
if(data) {
viewModel = new dealsPageModel(data);
var idList = "";
for (var i = 0; i< data.packageDeal.length; i++)
{
if (i == data.packageDeal.length -1)
{ idList += data.packageDeal[i].hotelId;
}
else
{idList += data.packageDeal[i].hotelId + ',';
}
}
var searchUrl = "http://terminal2.expedia.com/x/hotels?hotelids=" + idList + "&apikey=6weV4ksGIJ5eQhd58o2XTDwVo35lZf2S";
//another call to another api to return hotel specific info
jQuery.get(searchUrl, function ( )
{
for(var i=0; i<viewModel.dealList.length; i++)
{
var hotelId = viewModel.dealList[i].hotelId;
for(var i=0; i<data.HotelInfoList.HotelInfo.length; i++)
{
var url = HotelInfoList.HotelInfo[i].ThumbnailUrl;
var name = HotelInfoList.HotelInfo[i].Name;
}
// Get the hotelid from the current deal
// Loop through the hotelinfolist.hotelInfo and find out the url for the hotel idList
//Loop through the hotelinfolist.hotelInfo and find out the name for the hotel
viewModel.dealList.push(new deal(data.packageDeal[i], url, name));
}
ko.applyBindings(viewModel);
});
}
}
})
});
You loop through data.HotelInfoList.HotelInfo but operate on HotelInfoList.HotelInfo[i].ThumbnailUrl. The data. at the beginning is missing.
Also, place data in the callback function in jQuery.get:
jQuery.get(searchUrl, function(data){
// …
your data is in data.HotelInfoList not in HotelInfoList
your loop should be like this
for(var i=0; i<data.HotelInfoList.HotelInfo.length; i++)
{
var url = data.HotelInfoList.HotelInfo[i].ThumbnailUrl;
var name = data.HotelInfoList.HotelInfo[i].Name;
}

Categories