LaVOZs

The World’s Largest Online Community for Developers

'; swift - How can I merge 2 dictionaries into one array? - LavOzs.Com

My JSON data look like this image below. Now I wanna merge the value of Shop Type and Promotion into one to use as collection view data. How can I do that?

I just filter the response data from the server like this:

        var dataBanDau: [SDFilterModel] = []
        var quickData: [SDFilterModel] = []

        let filters: [SDFilterModel] = data

        self.filterEntries = filters

        //let nsarray = NSArray(array: self.filterEntries! , copyItems: true)
//            self.filterEntriesStoreConstant = nsarray as! Array

        self.dataBanDau = filters

        for i in 0..<self.dataBanDau.count {
            if self.dataBanDau[i].search_key.count == 0 {
                self.quickData.append(self.dataBanDau[i])
            }
        }

        self.quickData = self.quickData.filter {
            $0.type != "range"
        }

        DispatchQueue.main.async {
            //Note: Reload TableView
            self.quickFilterCollection.reloadData()
            completed(true)
        }
    }

the class SDFilterModel:

class SDFilterModel: DSBaseModel {
    var name = String()
    var type = String()
    var is_expanded = Int()
    var search_key = String()
    var filterEntries : [SDFilterModel]?

    override func copy(with zone: NSZone? = nil) -> Any {
        // This is the reason why `init(_ model: GameModel)`
        // must be required, because `GameModel` is not `final`.
        let copy = SDFilterModel(dict: self.dictionary)

        if let arrAttribute = NSArray(array: self.value , copyItems: true) as? [AttributeValueModel] {
            copy.value = arrAttribute
        }

        return copy
    }

    override init(dict: Dictionary<String, Any>) {
        super.init(dict: dict);
        value = self.valueParse()

        name = dict.getString(forKey: "name")
        type = dict.getString(forKey: "type")
        search_key = dict.getString(forKey: "search_key")
        is_expanded = dict.getInt(forKey: "is_expanded")!
    }


    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    var value: [AttributeValueModel] = [];

    func valueParse()-> [AttributeValueModel] {
        guard let childs  = (self.dictionary["value"]) as? [Dictionary<String, AnyObject>]
            else { return [] }

        var output: [AttributeValueModel] = [];

        for  aDict in childs {
            let item = AttributeValueModel(dict:aDict);

//            if type == .Range  && item.option_id == "0" {
//                item.setRangeOptionID(aValue: item.option_name!)
//            }
//
            output.append(item);
        }

        return output;
    }

enter image description here

Let be Assume you have let myArray = [1,2,3,4,5,6,7,8]

Now you wanted to square of each and every element in the array,

With for loop you do like this

for item in myArray {
    print(item * item) 
}

Now assume item = $0

With for map you jus do

myArray.map({ $0 * $0 })

Both will gave same output.


map : Use to do same operation on every element of array.

flatmap : It is used to flattern the array of array.

let myArr = [[1,2,3],[4,5,6,7]]

and you want o/p as [1,2,3,4,5,6,7]

So can get above output with myArr.flatMap({$0})


Now back to your question.

let reqArray = myModel.data.map({ $0.value }).flatMap({ $0 })

First, map gaves you array-of-array of key value but you need a single array, so for that you need to use flatmap.


You can take ref : https://medium.com/@Dougly/higher-order-functions-in-swift-sorted-map-filter-reduce-dff60b5b6adf

Create the models like this

struct Option {
    let name: String
    let searchKey: String
    let id: String
}

struct Model {
    let type: String
    let name: String
    let isExpanded: Bool
    let value: [Option]
}

You should get the options array values and join all the arrays

let models:[Model] = //...
let collectionViewArray = models.map { $0.value }.reduce([Option](), +)

Using for loop

var collectionViewArray = [Option]()
for model  in models {
    collectionViewArray.append(contentsOf: model.value)
}
Related
How do I merge two dictionaries in a single expression?
Create ArrayList from array
How do I check if an array includes a value in JavaScript?
How to append something to an array?
How do I sort a dictionary by value?
How can I add new keys to a dictionary?
Check if a given key already exists in a dictionary
Iterating over dictionaries using 'for' loops
How can I remove a specific item from an array?
For-each over an array in JavaScript