按键过滤API

时间:2020-04-21 06:46:49

标签: json reactjs api axios

伙计们有一些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 });
  });

欢呼

1 个答案:

答案 0 :(得分:0)

有多种方法可以执行此操作。如果您希望存在一个端点可以使用"Category": "food"来检索所有数据,那么前端工具就无能为力(实际上有几种方法,但是它们不再来自后端)。< / p>


问题说明

因此,我们假设当调用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")
    })
  });
相关问题