Create new object by using two others using map function

陌路散爱 提交于 2020-05-17 07:08:05

问题


Considering these two objects :

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"),
]

I want to create a new object called FinalObject :

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

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))
            }
        }
    }

How can I simplify this code using map function?


回答1:


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)
}


来源:https://stackoverflow.com/questions/61527981/create-new-object-by-using-two-others-using-map-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!