通过使用地图功能使用其他两个对象来创建新对象 [英] Create new object by using two others using map function

查看:55
本文介绍了通过使用地图功能使用其他两个对象来创建新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这两个对象:

struct Product {
    let id: Int
    let title: String
    let price: Int
    let categoryId: Int

}

struct Category {
    let id: Int
    let name: String
}

我还创建了这两个数据数组:

I created also those two data arrays :

let products = [
    Product(id: 1, title: "snake", price: 20, categoryId: 1),
    Product(id: 2, title: "soap", price: 20, categoryId: 2),
    Product(id: 3, title: "cream", price: 20, categoryId: 3),
    Product(id: 4, title: "dog", price: 20, categoryId: 1),
    Product(id: 5, title: "car", price: 20, categoryId: 4),
]

let categorieItems = [
    Category(id: 1, name: "animal"),
    Category(id: 2, name: "chemichal"),
    Category(id: 3, name: "food"),
    Category(id: 4, name: "travel"),
]

我想创建一个名为FinalObject的新对象:

I want to create a new object called FinalObject :

struct FinalProduct {
    let id: Int
    let title: String
    let price: Int
    let categoryName: String
}

这将通过使用Product和Category对象构造,以便在FinalProduct对象中具有名称.这是我使用两个有效的迭代循环完成的工作,但不是最佳实践:

This will be constructed by using Product and Category objects in order have the name inside the FinalProduct object. This is what I've done using two iteration loops which is working but is not the best practice :

var finalProducts = [FinalProduct]()
    for product in products {
        for cat in categorieItems {
            if product.categoryId == cat.id {
                finalProducts.append(FinalProduct(id: product.id, title: product.title, price: product.price, categoryName: cat.name))
            }
        }
    }

如何使用map函数简化此代码?

How can I simplify this code using map function?

推荐答案

您应该将categorieItems数组转换为字典,将id映射到实际项.然后,它真的很简单:

You should convert your categorieItems array into a dictionary, mapping id to the actual item. Then its really simple to do:

let finalProducts: [FinalProduct] = products.compactMap { 
     let categoryItem = categorieItems[$0.id]
     return FinalProduct(id: $0.id, title: $0.title, price: $0.price, categoryName: categoryItem.name)
}

这篇关于通过使用地图功能使用其他两个对象来创建新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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