Access variable item in JSON using Node.js

Asked

Viewed 108 times

0

I am accessing an API using Node.js, which returns the following JSON to me.

I need to access the field price, however the item PETR4: varies according to the symbol informed.

I can access until response.body.results.

How can I access the next item (which in this example is PETR4)?

{
  by: 'symbol',
  valid_key: true,
  results: {
    PETR4: {
      symbol: 'PETR4',
      name: 'Petróleo Brasileiro S.A. - Petrobras',
      region: 'Brazil/Sao Paolo',
      currency: 'BRL',
      market_time: [Object],
      market_cap: 255916,
      price: 19.31,
      change_percent: -1.63,
      updated_at: '2020-09-29 20:47:36'
    }
  },
  execution_time: 0.01,
  from_cache: false
}
  • Sometimes the field comes PETR4 and sometimes not, that’s it?

  • What can come beyond PETR4?

2 answers

6


You can use the function Object.values() to obtain the values of an object:

    const resposta = {
      by: 'symbol',
      valid_key: true,
      results: {
        PETR4: {
          symbol: 'PETR4',
          name: 'Petróleo Brasileiro S.A. - Petrobras',
          region: 'Brazil/Sao Paolo',
          currency: 'BRL',
          market_time: [Object],
          market_cap: 255916,
          price: 19.31,
          change_percent: -1.63,
          updated_at: '2020-09-29 20:47:36'
        }
      },
      execution_time: 0.01,
      from_cache: false
    };

    const { price } = Object.values(resposta.results)[0];

    console.log(price);

Object.values()

The method Object.values() returns a array values of the properties of a given object in the same order provided by for...in loop (the difference being that loop for-in also lists properties in the chain prototype).

0

Probably not the best way to access such property (including I will follow the post to learn), but you can use a for in to iterate on the property PETR4 or any other within the results.

Example:

const json = {
  by: 'symbol',
  valid_key: true,
  results: {
    PETR4: {
      symbol: 'PETR4',
      name: 'Petróleo Brasileiro S.A. - Petrobras',
      region: 'Brazil/Sao Paolo',
      currency: 'BRL',
      market_time: [Object],
      market_cap: 255916,
      price: 19.31,
      change_percent: -1.63,
      updated_at: '2020-09-29 20:47:36'
    }
  },
  execution_time: 0.01,
  from_cache: false
}

const ativo = json.results
let objName,
    objProperties

for (let i in ativo) {
  objName = i // pega valor da propriedade PETR4
  objProperties = ativo[i] // pega o objeto interno da PETR4
}

console.log(objName) // 'PETR4'
console.log(objProperties) // imprime o objeto interno da PETR4
console.log(objProperties.price) // imprime a propriedade que você precisa

Browser other questions tagged

You are not signed in. Login or sign up in order to post.