Mzalendo
Mzalendo

Reputation: 17

Mapping two arrays two one object in swift

I have two different arrays which am trying to map them to one object, using the information in the first array ModelOne id. I use two for loops to check if the id in model one appears in the second array if true create an object with model one id, name and array of all names in model two. From my implementation am not able to get the correct results.

// Model One
struct ModelOne: Codable {
    let id: Int
    let name: String
}

// Model two
struct ModelTwo: Codable {
    let id: Int
    let modelOneId: Int
    let name: String
}

var arrayOne = [ModelOne]()

arrayOne.append(ModelOne(id: 1, name: "One"))
arrayOne.append(ModelOne(id: 2, name: "Two"))

var arrayTwo = [ModelTwo]()

arrayTwo.append(ModelTwo(id: 1, modelOneId: 1, name: "Some name"))
arrayTwo.append(ModelTwo(id: 2, modelOneId: 1, name: "Other name"))
arrayTwo.append(ModelTwo(id: 1, modelOneId: 2, name: "Name one"))
arrayTwo.append(ModelTwo(id: 2, modelOneId: 2, name: "Name two"))

struct MappedModel {
    let id: Int
    let name: String
    let items: [String]
}

var arrayThree = [MappedModel]()

for i in arrayOne {
    for x in arrayTwo {
        if i.id == x.id {
            arrayThree.append(MappedModel(id: i.id, name: i.name, items: [x.name]))
        }
    }
}

Upvotes: 0

Views: 1605

Answers (1)

jnpdx
jnpdx

Reputation: 52387

If I'm interpreting the issue correctly, you want the MappedModel to have the id and name from ModelOne, with items containing all of the names from the ModelTwo where modelOneId matches the ModelOne id.

If so, this would do the trick:

var combined = arrayOne.map { item1 in
    MappedModel(id: item1.id, name: item1.name, items: arrayTwo.compactMap { $0.id == item1.id ? $0.name : nil})
}

Which yields:

[
  MappedModel(id: 1, name: "One", items: ["Some name", "Other name"]),
  MappedModel(id: 2, name: "Two", items: ["Name one", "Name two"])
]

Upvotes: 3

Related Questions