首页 > 解决方案 > 按密钥过滤 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 });
  });

干杯

标签: jsonreactjsapiaxios

解决方案


如您所料,有多种方法可以做到这一点。如果您希望应该存在一个端点来检索所有数据,"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")
    })
  });

推荐阅读