首页 > 解决方案 > 仅访问 Json 值的一部分

问题描述

我想参加 JSON 元素的一部分。我有 JSON 格式

{  
   "reservation":[  
      {  
         "resa":"1902211200-1802211330"
      },
      {  
         "resa":"1902221130-1902221230"
      }
   ]
}

对于每个预订,我只想访问最后的 4 个值 - 所以这里第一个 resa为1330 ,第二个为1230

<View>
    <FlatList
      data= {this.state.JsonList}
      renderItem={({item}) => <Text>{item.resa}.substring(17, 20)</Text>}
                  keyExtractor={(item, index) => index.toString()} />
</View>

substring 不起作用并显示单词 substring 但我找不到如何做。你能告诉我如何只显示 JSON 值的一部分吗?

标签: jsonreact-native

解决方案


{}如果您希望它正确计算子字符串,您应该包含完整的函数。之外的任何内容{}都将呈现为字符串。

<Text>{item.resa.substring(17, 21)}</Text>

您还需要更改它,以便在字符串中包含最后一个字符。否则,如果你使用substring(17, 20)那么你只会得到133而不是1330这样使用substring(17, 21)

let item = { resa: "1902211200-1802211330" }

console.log(item.resa.substring(17,20)) // 133
console.log(item.resa.substring(17,21)) // 1330
console.log(item.resa.substring(item.resa.length-4)) // you could use the length to calculate the substring
console.log(item.resa.slice(-4)) // you could always use slice


推荐阅读