user1227793
user1227793

Reputation: 305

Parsing a nested api response in Node

An API request like this: const response = await this.publicGetMarkets (params); is giving me a response that contains a list of markets in the following format:

{
  "markets": {
    "LINK-USD": {
    "market": "LINK-USD",
    "status": "ONLINE"
  },
  ...
}

As in the example here, my problem is that LINK-USD is changing for every market. How do I fix my code so that I can variables such as market, status in my code. I have written the following code snippet:

const market = this.safeValue (response, 'markets');
    const result = [];
    for (let i = 0; i < markets.length; i++) {
       const markets = this.safeString (markets, {}, {});
       const market = this.safeString (markets, 'market');
       const status = this.safeString (markets, 'status');
       result.push({
           'market': market,
           'status': status,
        });
     }
     return result;
    

Upvotes: 0

Views: 42

Answers (2)

Sohan
Sohan

Reputation: 588

    const responses = this.safeValue (response, 'markets');
    const result = [];
    for (let response of responses) {
       const market = responses.markets["LINK-USD"].market,
       status = responses.markets["LINK-USD"].status;
       result.push({market, status});
     }
     return result;

I hope this is what you asked for.

Upvotes: 0

charlietfl
charlietfl

Reputation: 171690

You can get an array of all the inner objects using Object.values(data.markets).

If you need to filter out unwanted properties that is a fairly simple mapping addition to this also

const data = {
  "markets": {
    "LINK-USD": {
      "market": "LINK-USD",
      "status": "ONLINE"
    },
    "LINK-EURO": {
      "market": "LINK-EURO",
      "status": "TBD"
    }
  }
}

const res = Object.values(data.markets)

console.log(res)

Upvotes: 1

Related Questions