Home > Software engineering >  Looping through Json Arrays from API
Looping through Json Arrays from API

Time:09-16

I am currently trying to loop and add each element of the quantity of each bid and ask which appears as bids[0][1], bids[1][1], bids[1][2] and add each element in the Array sequence. Any help will be greatly appreciated.

I tried adding the array but I am unable to turn the Json data to code here. Below is the API reference

I tried the code:

const binanceTrade = JSON.parse(data)

const bidsQuantity = binanceTrade.bids[0][1]

const askQuantity = binanceTrade.asks[0][1]


for(var i = 0; i<bidsQuantity.length; i  ){

  var j = 1;

  bidsQuantity = bidsQuantity.push(binanceTrade.bids[j][1])
  console.log(bidsQuantity)

  j  
  //bids[0][1]   bids[1][2]
}

And the public Binance API route for reference: https://api.binance.com/api/v3/depth?symbol=BTCUSDT&limit=5

CodePudding user response:

You can use reduce() to loop over the bids and asks arrays, totaling the second element of each item.

const binanceTrade = JSON.parse(data);
const bidsQuantity = binanceTrade.bids.reduce((acc, [_, quantity]) => acc   quantity, 0);
const asksQuantity = binanceTrade.asks.reduce((acc, [_, quantity]) => acc   quantity, 0);

CodePudding user response:

One approach would be to use map

const bidsQuantity = [];

binanceTrade.bids.map((bids) => {
    bidsQuantity.push(bids[1]);
});

You can do this again in a similar way for the asks

  • Related