Retrieve the highest value from 4 different JSON source URLs

After retrieving values from a JSON URL, using the following code:

$(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);

});

Is it possible to do the following?

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 am looking to set both low and high prices from PoloniexLastNXT, BittrexLastNXT, HitbtcLastNXT, and priceLastNXT. Can someone assist me with this?

Answer №1

To retrieve data from Poloneix, make sure you have the elements "PoloniexLowNXT" and "PoloniexHighNXT" set up in your code.

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

Answer №2

To enhance efficiency, consider using Promise.all along with a forEach method to iterate through the results. Instead of duplicating the implementation code, you can opt to create an array of settings and iterate over it to obtain and process the results:

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
    ]

  ]
  //other settings
];

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 prefer to stick with your existing repetitive approach, here's how you can fetch the minimum and maximum values:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover how to achieve the detail page view in Vue Js by clicking on an input field

I'm a beginner with Vuejs and I'm trying to display the detail page view when I click on an input field. <div class="form-group row"> <label for="name" class="col-sm-2 col-form-label">Name</label> ...

Python JSON load results in a Connection Forcibly Closed error

Overview: Utilizing Python 2.7 along with the urllib2 and json libraries, I am making an API call. However, upon running the script, I encounter the following error if the results count exceeds 20: Error: [Errno 10054] An existing connection was forcibl ...

Injecting live data into an input field within a table using Angular 4

Trying to create a dynamic row table with input fields in all cells. The loaded data is static, and I'm facing issues adding more data in the view. However, the functionality to add and delete rows is working fine. I have experimented with ngModel and ...

While working with AJAX, the variable value remains static and is not refreshed

My jQuery code successfully calls a REST Service and handles the response in the AJAX Success event. However, I'm facing an issue where the variable "SelectedVal" (document.getElementById('Text1').value) is not getting updated with each cli ...

How to target and set focus on dynamically generated input field when the ID is unknown

I am facing an issue with a jQuery/AJAX function that loads HTML form elements from the server. The form fields vary, and I want to set focus on the first available input field after the load is complete. I have tried: $(':input:enabled:visible:firs ...

Updating a value in a JSON file using node.js and preserving the changes

Can you guide me on updating a value in a JSON file and preserving it using node.js? The current content of the file is as follows: var file_content = fs.readFileSync(filename); var content = JSON.parse(file_content); var val1 = content.val1; I am now lo ...

What is the best way to add borders to the cities on interactive SVG maps?

I'm currently developing Interactive SVG Maps showcasing Turkey. The map consists of 81 cities, each represented by <g> elements, and their respective districts, created as child elements within the city elements. It's worth noting that the ...

Apply the "ng-class" directive only if there is an <a> element located after the specified element

My issue involves a list of items categorized by labels, with a search filter applied. The problem arises when the labels appear in the search results even though the lists themselves are empty. I need to hide the relevant label if there are no items prese ...

Associate text with a color from a predetermined list (JavaScript)

As I work on adding tags to my website for blog posts, I have a specific vision in mind. Each tag should be assigned a unique background color selected from a predefined array of theme colors. My goal is to assign the same background color to tags with id ...

Transforming a LinkedHashMap<String, MyClass> into a Java object

Is there a way to convert this JSON string structure into a Java object: { "summary": { "totalMR":4.599000000000903E12, "totalMA":1.9174920000386694E11, "totalQA":5.1111111181E9, "totalQR":1.000020666115264E11 }, "result": [{},{}], " ...

How to Create a Custom Callback Function for jQuery's .html

I am currently working with the following code: $.ajax({ type: 'GET', url: 'index.php?route=checkout/onepagecheckout/getpaypaldata', dataType: 'json', success: function(json) { ...

Resize a group of images to match the parent's width and height dimensions

I am working with a div that contains variously-sized images and is nested inside a parent container. <div id="parentContainer"> <div id="boxToScale"> <img src="http://placehold.it/350x150" /> <img src="http://placehold.it/150 ...

What is the best way to duplicate an entire webpage with all its content intact?

Is it possible to copy an entire page including images and CSS using Selenium? Traditional methods like ctrl + a or dragging the mouse over the page do not seem to work. How can this be achieved with Selenium without requiring an element to interact with? ...

Is there a way to prevent continuous repetition of JavaScript animated text?

I'm working on a code that displays letters and words one by one, but I can't figure out how to stop it from repeating. Can someone help me with this? <div id="changeText"></div> <script type="text/javascript"> var te ...

What is the correct approach for detecting object collisions in Phaser 3?

Hey everyone, I'm facing a problem and could use some assistance. Currently, I am trying to detect when two containers collide in my project. However, the issue is that the collision is being detected before the objects even start moving on screen. It ...

What could be causing this code to malfunction on jsfiddle?

Why doesn't this code from W3schools work on jsfiddle? I tried to implement it here: https://jsfiddle.net/u6qdfw5f/ <!DOCTYPE html> <html> <title>W3.CSS</title> <meta name="viewport" content="width=device-width, initial ...

Exploring the concept of template inheritance in Vue.js

Is there a way to implement template inheritance similar to Jade’s extends file.jade? I understand that composition can achieve the same result, but for components like the footer and header which are present on most pages except a few (e.g. login page), ...

Implement the CSS styles from the Parent Component into the Child Component using Angular 6

Is there a way to apply CSS from the Parent Component to style the child component in Angular 6? Please advise on how to approach this issue. How can we inherit the css styles from the Parent Component? <parent> <child> <p>hello ...

Automatically Assigning a Default Value to a Column Using SEQUELIZE ORM

When fetching data from a database using Sequelize ORM, I need to set a default value. Here is an example of the SQL query: SELECT a.affiliate_id, a.active AS current_state, IF(MAX(cn.contract_id) IS NULL ,0, IF(DATEDIFF(NOW(),MAX(cn.contract_date) ...

Link JSON in JavaScript using field identifiers

I've been working on incorporating JSON data into my JavaScript code, and the JSON structure I am dealing with is as follows: { "status":"ok", "count":5, "pages":1, "category":{ "id":85, "slug":"front-page-active", "title":"Front ...