用对象过滤嵌套数组 [英] Filter nested arrays with objects

查看:82
本文介绍了用对象过滤嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类别数组。每个Category实例都具有offers属性。

I have an array of Categories. Each Category instance has offers property.

class Category {
   var offers : [Offer]?
   var title : String?
   var id : Int?
}

class Offer {
    var type : String?
}

//global variable
var categories = [ categ1, categ2, ...]

如何按offer.type筛选类别?

How can I filter categories by offer.type ?

我已经尝试过:

return categories.map { (category) -> Category in
    let offers = category.offers?.filter { $0.type == myType }
    category.offers = offers
    return category
}

它可以工作,但是在调用函数第二次数组后为空。

It works but after calling function second time array becomes empty. Probably because offers were rewritten?

然后我尝试了此操作(产生了相同的错误结果):

Then I have tried this (produced same wrong result):

var resultCategories = [Category]()

for category in categories {
    guard let offers = category.offers else { continue }

    var newOffers = [Offer]()

    for offer in offers {
        if offer.type == myType {
            newOffers.append(offer)
        }
    }

    category.offers = newOffers
    resultCategories.append(category)
}

return resultCategories


推荐答案

您应该只需过滤器所有类别没有报价等于您的类型的报价。您可以通过以下方式实现此目标:

You should simply filter all categories that have no offers equals to your type. You can achieve that by:


  1. 过滤所有类别,并

  2. 在<$ c $内c> filter 检查当前报价是否包含 myType

  1. filter all your categories and
  2. inside the filter check if current offers contains the myType

代码:

let filtered = categories.filter { category in
    category.offers?.contains(where: { $0.type == myType }) ?? false
}

请注意, category.offers?。 [...] 是可选值,因此?如果左部分为 nil ,则false 返回 false

And note, that category.offers?.[...] is optional value, so the ?? false returns false as result if left part is nil.

UPD。


但是我希望类别会只提供类型为 A的商品。也许我没有正确描述问题。

But I expected that categories will have only offers with type = "A". Maybe I did not described the question accurately.

您可以通过创建新的类别

You can achieve that by creating a new Category.

let filtered = categories.compactMap { category -> Category? in
    guard let offers = category.offers?.filter({ $0.type == "A" }) else { return nil }
    let other = Category()
    other.offers = offers
    return other
}

也请注意,我使用的是 compactMap 。它使我可以过滤出报价为空或无 的类别。

Also note, i'm using compactMap. It allows me to filter categories with empty or nil offers out.

这篇关于用对象过滤嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆