json - 按密钥过滤 API
问题描述
嘿,伙计们有一些 JSON 数据和 API 试图弄清楚 API 将用于过滤其类别,目前只有“食物和物品”。这里是数据。
{
"id": 1587428052314,
"_id": "5e9e5599a3f3e540e9c6553c",
"Title": "Home Cleaning Sanitiser Box",
"Description": "This box has everything you need - right now!"
"Phone": "021881821921",
"Category": "food"
}
这是api:localhost:4000/api/user-listing/
我可以在我.then
的承诺链中以某种方式过滤它吗?
Axios.get("localhost:4000/api/user-listing")
.then((res) => {
// in here ?? this.setState({ listings: res.data });
});
干杯
解决方案
如您所料,有多种方法可以做到这一点。如果您希望应该存在一个端点来检索所有数据,"Category": "food"
那么您无法使用前端工具来处理它(实际上有几种方法,但它们不再来自后端)。
问题说明
所以我们假设当我们调用时localhost:4000/api/user-listing/
我们将收到一个包含多个对象的对象数组"Category": "food"
,然后我们假设我们已经从上面的端点检索到以下数据。
[{
"id": 1,
"_id": "5e9e5599a3f3e540e9c6553c-1",
"Title": "coke",
"Description": "This box has everything you need - right now!",
"Phone": "021881821921",
"Category": "drink"
},
{
"id": 2,
"_id": "5e9e5599a3f3e540e9c6553c-2",
"Title": "salmon",
"Description": "This box has everything you need - right now!",
"Phone": "021881821921",
"Category": "food"
},
{
"id": 3,
"_id": "5e9e5599a3f3e540e9c6553c-3",
"Title": "soda",
"Description": "This box has everything you need - right now!",
"Phone": "021881821921",
"Category": "drink"
},
{
"id": 4,
"_id": "5e9e5599a3f3e540e9c6553c-4",
"Title": "rice",
"Description": "This box has everything you need - right now!",
"Phone": "021881821921",
"Category": "food"
}
]
注意:我刚刚制作了这个示例数据数组以进行更多说明。您应该在代码中将其替换为您res.data
的。
过滤数据
要获取所有数据,"Category": "food"
我们可以简单地执行以下操作:
const arrayOfData = [{
"id": 1,
"_id": "5e9e5599a3f3e540e9c6553c-1",
"Title": "coke",
"Description": "This box has everything you need - right now!",
"Phone": "021881821921",
"Category": "drink"
},
{
"id": 2,
"_id": "5e9e5599a3f3e540e9c6553c-2",
"Title": "salmon",
"Description": "This box has everything you need - right now!",
"Phone": "021881821921",
"Category": "food"
},
{
"id": 3,
"_id": "5e9e5599a3f3e540e9c6553c-3",
"Title": "soda",
"Description": "This box has everything you need - right now!",
"Phone": "021881821921",
"Category": "drink"
},
{
"id": 4,
"_id": "5e9e5599a3f3e540e9c6553c-4",
"Title": "rice",
"Description": "This box has everything you need - right now!",
"Phone": "021881821921",
"Category": "food"
}
]
const newArray = arrayOfData.filter(data => data.Category === "food")
console.log(newArray)
更新
因此,当您更新问题时,如果您想处理其中的数据,.then
它将是这样的:
Axios.get("localhost:4000/api/user-listing")
.then((res) => {
this.setState({
listing: res.data.filter(data => data.Category === "food")
})
});
推荐阅读
- azure - Azure AD B2C 中的身份提供程序菜单未显示
- sql - 获取最近 90 天的记录 (SQL)
- c# - 与等效的 Webjobs 相比,队列触发的 Azure Functions 的等待时间非常长
- java - “无法执行保存操作:org.hibernate.exception.DataException:无法执行语句”使用 OpenXava?
- windows - 如果“DefineDynamicAssembly”不在 [System.AppDomain] 中,它在哪里?
- binary - (VB.NET) 如何读取二进制文件(不像 00 C8 而是 51200) - 汽车芯片调优软件
- javascript - 反应笑话 - 你不应该在外面使用
- ios - 无法连接 Firebase [IOS/Swift]
- java - 如何使 log4j2 每个日志调用记录一个文件?
- kubernetes - 如何使 XFS 配额在 DigitalOcean 上的 Kubernetes 卷中起作用?