0

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

1 Answer 1

3

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"]) ] 
Sign up to request clarification or add additional context in comments.

6 Comments

or using compactMap to avoid iterating the collection twice items: arrayTwo.compactMap { $0.id == item1.id ? $0.name : nil }
Note that OP is not using modelOneId if i.id == x.id { but not sure if that's what he needs
@LeoDabus I did note that. I'm making an assumption (that may be incorrect) that this is one of their issues, based on the naming scheme.
Yes I did notice that as well
@LeoDabus good idea with the compactMap -- adjusted. @Mzalendo see the revision history to see the original, which may be slightly more readable.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.