I have fetch some value from json url, with this
$(document).ready(function () {
function price(){
$.getJSON('https://poloniex.com/public?command=returnTicker', function(data){
document.getElementById('PoloniexLastNXT').innerHTML = (data.BTC_NXT.last);
document.getElementById('PoloniexBidNXT').innerHTML = (data.BTC_NXT.highestBid);
document.getElementById('PoloniexAskNXT').innerHTML = (data.BTC_NXT.lowestAsk);
});
$.getJSON('trade/libs/bittrex.php?i=nxt', function(data){
document.getElementById('BittrexLastNXT').innerHTML = (data.Bittrex);
document.getElementById('BittrexBidNXT').innerHTML = (data.BittrexBid);
document.getElementById('BittrexAskNXT').innerHTML = (data.BittrexAsk);
});
$.getJSON('trade/libs/hitbtc2.php?i=NXT', function(data){
document.getElementById('HitbtcLastNXT').innerHTML = (data.hitbtc);
document.getElementById('HitbtcBidNXT').innerHTML = (data.hitbtcbid);
document.getElementById('HitbtcAskNXT').innerHTML = (data.hitbtcask);
});
$.getJSON('https://vip.bitcoin.co.id/api/nxt_btc/ticker', function(data) {
document.getElementById('priceLastNXT').innerHTML = (data.ticker.last);
document.getElementById('priceLashBuyNXT').innerHTML = (data.ticker.buy);
document.getElementById('priceLashSellNXT').innerHTML = (data.ticker.sell);
document.title = "NXT " + (data.ticker.last);
});
}
setInterval(price, 3000);
});
can I do this
function getMax(array){
return Math.max.apply(Math,array);
}
var NxtBid = document.getElementById("PoloniexBidNXT");
var NxtBid2 = document.getElementById("BittrexBidNXT");
var NxtBid3 = document.getElementById("HitbtcBidNXT");
var NxtBid4 = document.getElementById("priceLashBuyNXT");
var NxtBid5 = [NxtBid, NxtBid2, NxtBid3, NxtBid4];
var NxtBid6 = getMax(NxtBid5);
document.getElementById("NxtBidMax").innerHTML = NxtBid6;
I want to set low price and hi price from PoloniexLastNXT, BittrexLastNXT,HitbtcLastNXT, priceLastNXT.someone can help me
For Poloneix you can use assuming you have elements for "PoloniexLowNXT" and "PoloniexHighNXT",
$.getJSON('https://poloniex.com/public?command=returnTicker', function(data){
document.getElementById('PoloniexLastNXT').innerHTML = (data.BTC_NXT.last);
document.getElementById('PoloniexBidNXT').innerHTML = (data.BTC_NXT.highestBid);
document.getElementById('PoloniexAskNXT').innerHTML = (data.BTC_NXT.lowestAsk);
document.getElementById('PoloniexLowNXT').innerHTML = (data.BTC_NXT.low24hr);
document.getElementById('PoloniexHighNXT').innerHTML = (data.BTC_NXT.high24hr);
});
You could try Promise.all and do a forEach on the results. Instead of repeating the implementation code you could create an array of settings and loop over it to get the result and process them:
const settings = [
[
"https://poloniex.com/public?command=returnTicker",//url
["#PoloniexLastNXT","#PoloniexBidNXT","#PoloniexAskNXT"],//elements to set
[//how to get value
data=>data.BTC_NXT.last,
data=>data.BTC_NXT.highestBid,
data=>data.BTC_NXT.lowestAsk
]
]
//others
];
Promise.all(
settings.map(
([url],index)=>
$.getJSON(setting(url))
.then(
data=>[data,settings[index]]
)
)
).then(
results=>{
var lowestLast=Infinity,highestLast=-Infinity;
results.forEach(
([data,[url,querySelectors,getters]])=>{
querySelectors.forEach(
(querySelector,index)=>
document.querySelector(querySelector).innerHTML=getters[index](data)
)
const last = getters[0](data);
if(last<lowestLast){
lowestLast=last;
}
if(last>highestLast){
highestLast=last;
}
}
)
return [lowestLast,highestLast];
}
).then(
([lowest,highest])=>{
console.log("lowest:",lowest,"highest:",highest);
}
).catch(
err=>console.warn("something went wrong:",err)
);
update
If you want to continue using your own repetitive implementation then you can get min and max in this way:
const numbers = [
new Number(trim(document.getElementById("PoloniexBidNXT").innerText)),
new Number(trim(document.getElementById("BittrexBidNXT").innerText)),
new Number(trim(document.getElementById("HitbtcBidNXT").innerText)),
new Number(trim(document.getElementById("priceLashBuyNXT".innerText)))
];
const lowest = Math.max.apply(null,numbers);
const highest = Math.min.apply(null,numbers);
Related
So I'm coding this
https://vercel.com/eduardodevolmedo/jsd-aily
function executeWeekly() {
fetch("/data.json")
.then(function (resp) {
return resp.json();
})
.then(function (data) {
currentW = data[0].timeframes.weekly.current
previousW = data[0].timeframes.weekly.previous
currentWork.innerHTML = `${currentW}${hrs}`
previousWork.innerHTML = `${lastWeek} - ${previousW}${hrs}`
//DATA FROM PLAY
currentP = data[1].timeframes.weekly.current
previousP = data[1].timeframes.weekly.previous
currentPlay.innerHTML = `${currentP}${hrs}`
previousPlay.innerHTML = `${lastWeek} - ${previousP}${hrs}`
//DATA FROM STUDY
currentS = data[2].timeframes.weekly.current
previousS = data[2].timeframes.weekly.previous
currentStudy.innerHTML = `${currentS}${hrs}`
previousStudy.innerHTML = `${lastWeek} - ${previousS}${hrs}`
//DATA FROM EXERCISE
currentE = data[3].timeframes.weekly.current
previousE = data[3].timeframes.weekly.previous
console.log(currentE, previousE)
currentExercise.innerHTML = `${currentE}${hrs}`
previousExercise.innerHTML = `${lastWeek} - ${previousE}${hrs}`
//DATA FROM SOCIAL
currentSO = data[4].timeframes.weekly.current;
previousSO = data[4].timeframes.weekly.previous;
currentSocial.innerHTML = `${currentSO}${hrs}`
previousSocial.innerHTML = `${lastWeek} - ${previousSO}${hrs}`
//DATA FROM SELFCARE
currentSE = data[5].timeframes.weekly.current;
previousSE = data[5].timeframes.weekly.previous;
currentSelfcare.innerHTML = `${currentSE}${hrs}`
previousSelfcare.innerHTML = `${lastWeek} - ${previousSE}${hrs}`
})
eachBlock.forEach(el => el.classList.toggle('animatedBox'))
}
function executeDaily() {
fetch("/data.json")
.then(function (resp) {
return resp.json();
})
.then(function (data) {
//DATA FROM WORK
currentW = data[0].timeframes.daily.current
previousW = data[0].timeframes.daily.previous
currentWork.innerHTML = `${currentW}${hrs}`
previousWork.innerHTML = `${lastDay} - ${previousW}${hrs}`
//DATA FROM PLAY
currentP = data[1].timeframes.daily.current
previousP = data[1].timeframes.daily.previous
currentPlay.innerHTML = `${currentP}${hrs}`
previousPlay.innerHTML = `${lastDay} - ${previousP}${hrs}`
//DATA FROM STUDY
currentS = data[2].timeframes.daily.current
previousS = data[2].timeframes.daily.previous
currentStudy.innerHTML = `${currentS}${hrs}`
previousStudy.innerHTML = `${lastDay} - ${previousS}${hrs}`
//DATA FROM EXERCISE
currentE = data[3].timeframes.daily.current
previousE = data[3].timeframes.daily.previous
currentExercise.innerHTML = `${currentE}${hrs}`
previousExercise.innerHTML = `${lastDay} - ${previousE}${hrs}`
//DATA FROM SOCIAL
currentSO = data[4].timeframes.daily.current;
previousSO = data[4].timeframes.daily.previous;
currentSocial.innerHTML = `${currentSO}${hrs}`
previousSocial.innerHTML = `${lastDay} - ${previousSO}${hrs}`
//DATA FROM SELFCARE
currentSE = data[5].timeframes.daily.current;
previousSE = data[5].timeframes.daily.previous;
currentSelfcare.innerHTML = `${currentSE}${hrs}`
previousSelfcare.innerHTML = `${lastDay} - ${previousSE}${hrs}`
})
eachBlock.forEach(el => el.classList.toggle('animatedBox'))
}
So, im running the exact same function at monthly, and daily.
Which is now working, but i had to copy the same code for the same functions, so I was thinking in a way I could do it in less lines of code. So, my idea was to assign a string to a variable, and then making it a string, using JSON.stringify()
let z = weekly
let x = JSON.stringify(z)
Then i thought, that I would assing a variable to each button on html, using an if statement, for example if the button value was "daily" then z would be daily, and the function would run using daily as that argument.
And then, I just add it like a variable, depending on what i want:
currentW = data[0].timeframes.z.current
instead of:
currentW = data[0].timeframes.daily.current
In that way, I would only need to use one function.
But that doesn't seems to work.
How can I do this? Is there any way?
If you want to check the code further:
https://github.com/EduardoDevOlmedo/JSDaily
You have to access the object member as if the object was an associative array:
currentW = data[0].timeframes[z].current
Solved:
Accessing to
this.innerHTML
and assigning the value to z.
function check(){
value = this.innerHTML
execute(value)
}
As the title states, I'm having trouble with Promises in Parse.
I'm struggling to firstly understand exactly how Promises themselves work, especially in Parse.
I have been stuck on this for about three weeks and the closest I've come to a solution is having an empty array returned.
What I'm trying to do is scrape a site and then create objects from the table (this is working)
Where there trouble comes in, is I am then running a for loop on the results and querying each Dam name to get the resulting objectid from the database.
Here is my code:
var c = new Crawler({
maxConnections: 10,
// This will be called for each crawled page
callback: function(err, res, done) {
if (err) {
console.log(err);
} else {
var $ = res.$;
// $ is Cheerio by default
//a lean implementation of core jQuery designed specifically for the server
console.log($("title").text());
}
done();
}
});
The Function which Creates objects from the Dom and adds them to an array:
function getDamObjects(Dom) {
var dom = Dom;
var LevelObjects = [];
for (i = 1; i < dom.length - 1; i++) {
var TableRow = dom.eq(i);
var NameString = TableRow.children().eq(0).text();
var RiverString = TableRow.children().eq(1).text();
var FSCString = TableRow.children().eq(4).text();
var ThisWeekString = TableRow.children().eq(5).text();
var LastWeekString = TableRow.children().eq(6).text();
var LastYearString = TableRow.children().eq(7).text();
NameString = NameString.replace('#', '');
NameString = NameString.replace('$', '');
NameString = NameString.replace('&', '');
NameString = NameString.replace('#', '');
ThisWeekString = ThisWeekString.replace('#', '');
ThisWeekString = ThisWeekString.replace('$', '');
ThisWeekString = ThisWeekString.replace('&', '');
ThisWeekString = ThisWeekString.replace('#', '');
LastWeekString = LastWeekString.replace('#', '');
LastWeekString = LastWeekString.replace('$', '');
LastWeekString = LastWeekString.replace('&', '');
LastWeekString = LastWeekString.replace('#', '');
LastYearString = LastYearString.replace('#', '');
LastYearString = LastYearString.replace('$', '');
LastYearString = LastYearString.replace('&', '');
LastYearString = LastYearString.replace('#', '');
var level = {};
/*
getDamObject(NameString).then(function(DamObject){
let DamID = DamObject.id;
*/
level['Dam'] = NameString; //DamID;
level['ThisWeek'] = ThisWeekString;
level['LastWeek'] = LastWeekString;
level['LastYear'] = LastYearString;
LevelObjects.push(level);
};
return LevelObjects;
};
The Get Dam Object Code:
function getDamObject(Dam) {
var promise = new Parse.Promise();
var query = new Parse.Query("DayZeroDams");
query.equalTo("Name", Dam);
query.first().then(function(DamObject) {
promise.resolve(DamObject);
}, function(error) {
promise.reject(error);
});
return promise;
}
The Cloud Code Called:
Parse.Cloud.define('jsdom', function(request, response) {
c.queue([{
uri: 'xxxxxx',
// The global callback won't be called
callback: function(err, res, done) {
if (err) {
response.error(err);
} else {
var $ = res.$;
var ResultsArray = [];
var dom = res.$('#mainContent_tw').children('tr');
return Parse.Promise.as().then(function() {
var promise = Parse.Promise.as();
var LevelObjects = getDamObjects(dom);
_.each(LevelObjects, function(DamLevel) {
promise = promise.then(function() {
var Name = DamLevel["Dam"];
var query = new Parse.Query("DayZeroDams");
query.equalTo("Name", Name);
return query.first().then(function(result) {
let damID = result.id;
ResultsArray.push(damID);
return Parse.Promise.as();
}, function(error) {
response.error(error);
});
});
});
return promise;
}).then(function() {
response.success(ResultsArray);
}, function(error) {
response.error(error);
});
//response.success(LevelObjects);
}
done();
}
}]);
});
Please take note that I am fairly novice when it comes to Javascript, I have only recently started learning it in order to work with my server code.
Convert getDamObjects into an async function and then await the result of each row, pushing it to the array:
function replaceSymbols(input) {
return input.replace(/[#\$&#]/g, '');
}
async function getDamObjects(Dom) {
const dom = Dom;
const levelObjects = [];
for (let i = 1; i < dom.length - 1; i++) {
const children = dom.eq(i).children();
const NameString = replaceSymbols(children.eq(0).text());
const RiverString = children.eq(1).text();
const FSCString = children.eq(4).text();
const ThisWeek = replaceSymbols(children.eq(5).text());
const LastWeek = replaceSymbols(children.eq(6).text());
const LastYear = replaceSymbols(children.eq(7).text());
const Dam = await getDamObject(NameString);
levelObjects.push({
Dam,
ThisWeek,
LastWeek,
LastYear,
});
}
return levelObjects;
}
Remember that now that getDamObjects is an async function, it will return a Promise that resolves to the array once iterations are complete. Consume it using await getDamObjects in another async function (or use .then)
i was tested to the IdentyfyTask.
But I could not get a response before the value addCallback.
i want to the pnu values.
But pnu vaule was alwayes undefined...
my code is follows.
function poiClick(){
agmap.addEvent("click", function(evt){
getPoi= krcgis.Function.PoiClick(agmap ,evt);
console.log("X === ",getPoi.x);
console.log("Y === ",getPoi.y);
console.log("PNU === ",getPoi.pnu);
});
}
PoiClick : function(map, evt) {
poiInfo = {};
poiInfo.x =evt.mapPoint.x;
poiInfo.y =evt.mapPoint.y;
var targetLayerId = 'LP_PA_CBND';
var url = map.Layers.getLayerInfo(targetLayerId).SVC_URL;
var map = map.getMap();
//파라미터 설정.
var idParams = new krcgis.core.tasks.IdentifyParameters();
idParams.geometry = evt.mapPoint;
idParams.mapExtent = map.extent;
idParams.returnGeometry = true;
idParams.tolerance = 0;
idParams.layerOption = krcgis.core.tasks.IdentifyParameters.LAYER_OPTION_ALL;
idParams.width = map.width;
idParams.height = map.height;
idTask = new krcgis.core.tasks.IdentyfyTask(url);
idTask
.execute(idParams)
.addCallback(function (response) {
if (response) {
poiInfo.pnu =response[0].value;
}
});
return poiInfo;
}
The results were as follows.
IdentifyTask returns a IdentifyResult object. so you code response[0].value will be undefined.
you should use something like response[0].feature.attributes.PNU
I am trying to pass product into the find() function that contains a .toArray() anonymous function containing both error and array. Unfortunately this entire find() function runs within an iteration and only the first value goes in. How do I pass product to the callbacks?
var find = function(product,callbacks){
foos.find({
"foo": product.bars,
}).toArray(function (error, array) {
if(error){
callbacks.error(product,error);
} else if (array.length == 0) {
callbacks.none(product);
} else {
callbacks.exists(product);
}
});
}
Before this function i was processing products with forEach() then had this run in a callback within that. This was big trouble. Processed products with a regular for and now it works.
Old code
var products = function(data,callback){
products.forEach(function(product){
insert.product_id = product.id;
var variants = product.variants;
variants.forEach(function(variant){
insert.sku = variant.sku;
insert.variant_id = variant.id;
return callback(insert);
});
});
}
New code
var products = function(data){
var insert = [];
var products = data.products;
for(var pKey in products){
var product = products[pKey];
var variants = product.variants;
var set = {}
set.product_id = product.id;
for(var vKey in variants){
var variant = variants[vKey];
set.sku = variant.sku;
set.variant_id = variant.id;
insert.push(set);
}
}
return insert;
}
may be you can help me. How can I create global object and function that return object values by id?
Example:
var chat = {
data : {
friends: {}
}
}
....
/*
JSON DATA RETURNED:
{"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
*/
onSuccess: function(f){
chat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends.push(f.users[i])
}
}
How can I create a new function (It will return values by friend_id)?
get_data_by_id: function (what, friend_id) {
/*obj.what = getfrom_globalobject(chat.data.friends???)*/
}
Example of use:
var friend_name = get_data_by_id(name, 62);
var friend_username = get_data_by_id(username, 62);
var friend_avatar = get_data_by_id(thumb, 62);
Try:
get_data_by_id: function (what, friend_id) {
return chat.data.friends[friend_id][what];
}
... but use it like:
var friend_name = get_data_by_id('name', 62);
...and set up the mapping with:
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i];
}
You cannot .push() to an object. Objects are key => value mappings, so you need to use char.data.friends[somekey] = f.users[i];
If you really just want a list with numeric keys, make x5fastchat.data.friends an array: x5fastchat.data.friends = [];
However, since you want to be able to access the elements by friend_id, do the following:
onSuccess: function(f){
x5fastchat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i]
}
}
get_data_by_id: function (what, friend_id) {
obj[what] = chat.data.friends[friend_id][what];
}
Note the obj[what] instead of your original obj.what: When writing obj.what, what is handled like a string, so it's equal to obj['what'] - but since it's a function argument you want obj[what].
Take a look at the following code. You can simply copy paste it into an HTML file and open it. click "go" and you should see the result. let me know if I did not understand you correctly. :
<script>
myObj = { "field1" : { "key1a" : "value1a" }, "field2" : "value2" }
function go()
{
findField(myObj, ["field2"])
findField(myObj, ["field1","key1a"])
}
function findField( obj, fields)
{
var myVal = obj;
for ( var i in fields )
{
myVal = myVal[fields[i]]
}
alert("your value is [" + myVal + "]");
}
</script>
<button onclick="go()">Go</button>
I would recommend using the friend objects rather than getting them by id and name.
DATA = {"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
// simple data store definition
Store = {items:{}};
NewStore = function(items){
var store = Object.create(Store);
store.items = items || {};
return store
};
Store.put = function(id, item){this.items[id] = item;};
Store.get = function(id){ return this.items[id]; };
Store.remove = function(id){ delete this.items[id]; };
Store.clear = function(){ this.items = {}; };
// example
var chat = {
data : {
friends : NewStore()
}
}
// after data loaded
chat.data.friends.clear();
for( var i = 0; i < DATA.users.length; i += 1 ){
var user = DATA.users[i];
chat.data.friends.put( user.friend_id, user );
}
getFriend = function(id){ return chat.data.friends.get( id ); }
var friend = getFriend(66);
console.log(friend.name);
console.log(friend.username);
console.log(friend.thumb);