[英]TSX React - How to index JSON API Data with multiple JSON Objects
I am trying to use useFetch
to get API data and index to get a specific value.我正在尝试使用
useFetch
获取 API 数据和索引以获取特定值。
This is the current code:这是当前代码:
const { isLoading, error, data } = useFetch("https://public-api.solscan.io/account/tokens?account=C9XzDbZrZkJ75EvEeb641PQ5Q9kDiN2nFugdyAXqGip1");
const dataStarsStaked = JSON.stringify(data, ["0", "tokenAddress", "tokenAmount", "uiAmount"], 0);
which returns data
:返回
data
:
[{"tokenAddress":"4q5UBXJxE91BZKX548qhU8i5QBWvZdXzS3RZwfTgLQda","tokenAmount":{"uiAmount":253847.899902}},{"tokenAddress":"HCgybxq5Upy8Mccihrp7EsmwwFqYZtrHrsmsKwtGXLgW","tokenAmount":{"uiAmount":6864373.022357}},{"tokenAddress":"HkNK7BL5pSUUzc6ns1mHW5JnzbSG4S9u2QdR3cUuyzSa","tokenAmount":{"uiAmount":678}}]
I am trying to get the value of uiAmount of tokenAddress: HCgybxq5Upy8Mccihrp7EsmwwFqYZtrHrsmsKwtGXLgW
.我正在尝试获取 uiAmount of
tokenAddress: HCgybxq5Upy8Mccihrp7EsmwwFqYZtrHrsmsKwtGXLgW
的值。 How do I do this?我该怎么做呢? I am not sure how to index this.
我不知道如何索引这个。 Thanks!
谢谢!
You can search the data array:您可以搜索数据数组:
data.find(x => x.tokenAddress === "HCgybxq5Upy8Mccihrp7EsmwwFqYZtrHrsmsKwtGXLgW");
To get rid of the typescript errors, you need to define types (use something similar to this, but change any[]
to the array of object types the api is returning):要消除 typescript 错误,您需要定义类型(使用与此类似的内容,但将
any[]
更改为 api 返回的 object 类型的数组):
interface YourFetchResult {
data: any[];
isLoading: boolean;
error?: string;
}
const { isLoading, error, data }: FetchResult = useFetch(...)
you need to apply a for loop and have a condition that detects the string see below您需要应用 for 循环并具有检测字符串的条件,请参见下文
let x = [{"tokenAddress":"4q5UBXJxE91BZKX548qhU8i5QBWvZdXzS3RZwfTgLQda","tokenAmount":{"uiAmount":253847.899902}},{"tokenAddress":"HCgybxq5Upy8Mccihrp7EsmwwFqYZtrHrsmsKwtGXLgW","tokenAmount":{"uiAmount":6864373.022357}},{"tokenAddress":"HkNK7BL5pSUUzc6ns1mHW5JnzbSG4S9u2QdR3cUuyzSa","tokenAmount":{"uiAmount":678}}]
for (let i = 0; i < x.length; i++) {
if(x[i].tokenAddress==="HCgybxq5Upy8Mccihrp7EsmwwFqYZtrHrsmsKwtGXLgW") {
console.log(x[i].tokenAmount)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.