按密钥筛选API



Heys的人有一些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")
})
});

最新更新