在React Native中重构JSON格式

时间:2019-07-11 16:35:54

标签: json reactjs react-native

我从汇率API获得了JSON数据,但是当我尝试在flatlist中显示它时,我得到了一个错误:Invariant violation tried to get frame for out of range index nan,然后我意识到这不是我想要的JSON格式。数据是:

{  
"rates":{  
  "CAD":0.1669423548,
  "HKD":1.0,
  "PLN":0.4835606816
},
"base":"EUR",
"date":"2019-07-11"
}

我希望它看起来像

{  
"rates":[  
  {  
     "currency":"hkd",
     "rate":"1",
     "base":"EUR",
     "date":"2019-07-11"
  },
     {  
     "currency":"CAD",
     "rate":"0.1669423548",
     "base":"EUR",
     "date":"2019-07-11"
  },
   {  
     "currency":"PLN",
     "rate":"0.4835606816",
     "base":"EUR",
     "date":"2019-07-11"
  },
]
}

这就是我获取数据的方式

async _getRateData() {

const response = await fetch('https://api.exchangeratesapi.io/latest?base=EUR');
const json = await response.json();

this.setState({
  loading: false,
  dataSource: json.base,
  rates: json.rates,
  date: json.date,
  base: json.base,
})
 }

我是新来的本地人,我不知道该怎么做

1 个答案:

答案 0 :(得分:0)

您可以将_getRateData()方法更新为此:

async _getRateData() {

  const response = await fetch('https://api.exchangeratesapi.io/latest?base=EUR');
  const json = await response.json();

  // setting up data object from API endpoint to work with
  const data = {
    rates: json.rates,
    date: json.date,
    base: json.base,
  }

  // data transformation
  const newData = {
    // Object.keys method return array of all keys in rates obejct
    rates: Object.keys(data.rates).map((currency, idx) => {
      // then with map function you can map all keys
      // and construct your own data structure
      return {
        currency, // first element currency (the same as currency: currency, es6 shortcode)
        rate: data.rates[currency], // accessing rates element by key
        base: data.base, // adding rest of the data
        date: data.date
      };
    })
  };

  // setting data to state
  this.setState({
    loading: false,
    dataSource: json.base,
    rates: newData.rates // set to rates only array
  })

}

具有简单数据的演示:https://codesandbox.io/s/vibrant-carson-d5idp