1

I'm working with some script and I would like to ask how to display on the console a specific json value.

For example, I have script:

Promise.all([
  fetch('https://blockchain.info/balance?active=3C6WPNa5zNQjYi2RfRmt9WUVux7V4xbDmo').then(resp => resp.json()),
  fetch('https://api.binance.com/api/v3/avgPrice?symbol=BTCEUR').then(resp => resp.json()),
]).then(console.log)

output:

[{
    3C6WPNa5zNQjYi2RfRmt9WUVux7V4xbDmo: {
      final_balance: 185653,
      n_tx: 1,
      total_received: 185653
    }
  }, {
    mins: 5,
    price: "19230.49330261"
  }]

I want to console price and final_balance. Best regards!

WhoAmI
  • 33
  • 5

1 Answers1

0

One way you could achieve this is by flattening the array and objects within because there's no predefined structure of what the output looks like.

Here, I'm assuming the output you mentioned is always an array of objects.

const flattenObject = (obj = {}) =>
  Object.keys(obj || {}).reduce((acc, cur) => {
    if (typeof obj[cur] === "object") {
      acc = { ...acc, ...flattenObject(obj[cur]) };
    } else {
      acc[cur] = obj[cur];
    }
    return acc;
  }, {});

const outputs = [
  {
    "3C6WPNa5zNQjYi2RfRmt9WUVux7V4xbDmo": {
      final_balance: 185653,
      n_tx: 1,
      total_received: 185653,
    },
  },
  {
    mins: 5,
    price: "19230.49330261",
  },
];

outputs.forEach((output) => {
  const flatOutput = flattenObject(output);
  console.log("flatOutput:", flatOutput);
  if (flatOutput.final_balance) {
    console.log("final_balance:", flatOutput.final_balance);
  }
  if (flatOutput.price) {
    console.log("price:", flatOutput.price);
  }
});
axelmukwena
  • 779
  • 7
  • 24