简体   繁体   中英

How to display specific JSON data from an API

I'm using got for requests.

Code:

const response = await got(`https://airapi.airly.eu/v2/measurements/installation?installationId=204`, {
        headers: {
            apikey: `API_KEY`
        },
        json: true
    });

console.log(response.body.current.values);

Output:

[ { name: 'PM1', value: 20.72 },
  { name: 'PM25', value: 32.43 },
  { name: 'PM10', value: 61.22 },
  { name: 'PRESSURE', value: 1028.46 },
  { name: 'HUMIDITY', value: 91.59 },
  { name: 'TEMPERATURE', value: 10.87 } ]

Now, I want to display it to the user in this format:

PM1: 20.72 µg/m3 
PM25: 32.43 µg/m3 
PM10: 61.22 µg/m3 

My question is: What's the best way to do that? In the future, I also want to use a library like https://www.chunqiuyiyu.com/ervy/ , so it would be nice to have this data somehow separated. I hope that I've made myself clear :)

Lots of ways to do this (without resorting to a library). One way:

 let data = [ { name: 'PM1', value: 20.72 }, { name: 'PM25', value: 32.43 }, { name: 'PM10', value: 61.22 }, { name: 'PRESSURE', value: 1028.46 }, { name: 'HUMIDITY', value: 91.59 }, { name: 'TEMPERATURE', value: 10.87 } ]; data.forEach(v => console.log(`${v.name}: ${v.value} µg/m3`)); 

It looks like Envy uses a specific structure for its data, so you first need to convert your existing data:

const data = arr.map(el => ({ ...el, key: el.name }));

Then you can map over the elements and join them with line breaks afterwards, printing them to the console.

Demo:

 const arr = [{"name":"PM1","value":20.72},{"name":"PM25","value":32.43},{"name":"PM10","value":61.22},{"name":"PRESSURE","value":1028.46},{"name":"HUMIDITY","value":91.59},{"name":"TEMPERATURE","value":10.87}]; // create an envy structure from the original data using `map` const data = arr.map(el => ({ ...el, key: el.name })); // `map` over that data and return an array of strings // separated by line breaks const str = data.map(el => `${el.key}: ${el.value} µg/m3`).join('\\n'); console.log(str); 

simply you can do like

 var data = [ { name: 'PM1', value: 20.72 },
  { name: 'PM25', value: 32.43 },
  { name: 'PM10', value: 61.22 },
  { name: 'PRESSURE', value: 1028.46 },
  { name: 'HUMIDITY', value: 91.59 },
  { name: 'TEMPERATURE', value: 10.87 } ];


  $.each(data, function (i) {
   console.log(data[i].name+':'+data[i].value);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM