You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按对象名称排序嵌套对象数组并适配React Native FlatList?

解决方案:将汇率对象转换为排序后的数组适配FlatList

实现代码

// 假设已获取到API返回的curr对象
const sortedCurrencyArray = Object.entries(curr.rates)
  // 按货币代码字母顺序升序排序
  .sort(([codeA], [codeB]) => codeA.localeCompare(codeB))
  // 映射为目标数组格式
  .map(([id, data]) => ({
    id,
    currency_name: data.currency_name,
    rate: data.rate,
    rate_for_amount: data.rate_for_amount
  }));

步骤说明

  1. 转换键值对数组:Object.entries(curr.rates) 将rates对象拆解为[货币代码, 对应数据]的键值对数组,方便后续排序和格式转换。
  2. 按货币代码排序:通过localeCompare方法对货币代码进行字母序升序排序,确保结果按AUD、CAD、USD的顺序排列。
  3. 映射为目标格式:将每个键值对转换为FlatList适配的对象结构,把原货币代码作为id字段(满足FlatList对唯一标识的要求),保留其他汇率相关字段。

在FlatList中使用示例

import { FlatList, View, Text } from 'react-native';

// ...

<FlatList
  data={sortedCurrencyArray}
  keyExtractor={(item) => item.id}
  renderItem={({ item }) => (
    <View style={{ paddingVertical: 12, paddingHorizontal: 16, borderBottomWidth: 1, borderColor: '#eee' }}>
      <Text style={{ fontSize: 16, fontWeight: 'bold' }}>{item.id}</Text>
      <Text style={{ fontSize: 14, color: '#666' }}>{item.currency_name}</Text>
      <Text style={{ marginTop: 4, fontSize: 14 }}>汇率: {item.rate}</Text>
      <Text style={{ fontSize: 14 }}>10 EUR可兑换: {item.rate_for_amount}</Text>
    </View>
  )}
/>

内容的提问来源于stack exchange,提问作者BenoHiT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 01:51:09