Swift 中的 JSON 和 Node 如何在 GET 请求中实现类别的过滤器



简单地说,我想将完整的json数组过滤为三个类别。

让我告诉你我在说什么

var menu = [
{
id: "coffe",
name: "Espresso",
description: "",
image: ''
},
{
id: "coffe",
name: "Latte",
description: "",
image: ''
},
{
id: "coffe-nosugar",
name: "Hot Chocolate",
description: "",
image: ''
},
{
id: "tea",
name: "Red Tea",
description: " ",
amount: "0.0",
image: ''
},
{
id: "tea",
name: "Green Tea",
description: " ",
amount: "0.0",
image: ''
},
{
id: "fresh-juice",
name: "Orange",
description: "",
amount: "0.0",
image: ''
}
]

现在,任何人都可以告诉我如何将这些数据分为三类

  • 咖啡

现在我在我的节点JS中使用它

app.get('/menu', (req, res) => res.json(menu))

要在没有任何过滤器的情况下显示所有库存商品,只需转到 http://APIurl/menu

struct Menu: Codable {
var id: String
var name: String
var description: String
var image: String
var amount: String
var category: String
}
var menu = "[rn  {rn    "name": "Espresso",rn    "id": "coffe",rn    "description": "",rn    "image": "",rn    "amount": "0.0",rn    "category": "Coffee"rn  },rn  {rn    "name": "Latte",rn    "id": "coffe",rn    "description": "",rn    "image": "",rn    "amount": "0.0",rn    "category": "Coffee"rn  },rn  {rn    "id": "coffe-nosugar",rn    "name": "Hot Chocolate",rn    "description": "",rn    "image": "",rn    "amount": "0.0",rn    "category": "Tea"rn  },rn  {rn    "id": "tea",rn    "name": "Red Tea",rn    "description": " ",rn    "amount": "0.0",rn    "image": "",rn    "category": "Tea"rn  },rn  {rn    "id": "tea",rn    "name": "Green Tea",rn    "description": " ",rn    "amount": "0.0",rn    "image": "",rn    "category": "Tea"rn  },rn  {rn    "id": "fresh-juice",rn    "name": "Orange",rn    "description": "",rn    "amount": "0.0",rn    "image": "",rn    "category": "Juice"rn  }rn]"
if let data = menu.data(using: .utf8) {
let decoder = JSONDecoder()
do {
let menus = try decoder.decode([Menu].self, from: data)
let categorizedMenu = Dictionary(grouping: menus) { $0.category }
} catch {
print(error.localizedDescription)
}
}

这一行可以解决问题,这里发生的事情是我们按属性对对象数组进行分组,即类别

Dictionary(grouping: menus) { $0.category }

顺便说一下,在我的回答中,我添加了一个新属性,它是对象中的类别,不建议按 id 对对象进行分组,因为id始终是唯一的

var menu: [MenuItems] = []
override func viewDidLoad() {
super.viewDidLoad()

fetchInventory { menu in
// Answer: This is will eliminate items with id == "1".
menu = (menu?.filter { $0.id != "1"})! 
//Show All Items
self.menu = menu! 
self.tableView.reloadData()
}
}

感谢金元贞!在此处查看完整帖子:如何使用 Swift 实现数组过滤器?

最新更新