AlexR
AlexR

Reputation: 5634

Merging a complex data structure of NSArray and NSDictionary

I have the following data structure Snapshot which is a combination of nested arrays and dictionaries:

{"Snapshot": {
    "ask": [
        {
            "price": 101.42,
            "size": 7
        },
        {
            "price": 101.85,
            "size": 5
        }
    ],
    "bid": [
        {
            "price": 89.72,
            "size": 79
        },
        {
            "price": 89.71,
            "size": 158
        }
    ]
}}

The existing structure from above should be updated by the price and size entries in the following dictionary / array structure:

{"Refresh": {
    "ask": [],
    "bid": [
        {
            "price": 89.71,
            "size": 666
        }
    ],
}}

In this example, the value size for the bid item which has the price: 89.71 should be updated from 158 to 666. If the price does not exist yet, a new item with the price and size from the Refresh data structure should be added. If size = 0, the price and size item should be removed.

I have tried to do this with the methods addEntriesFromDictionary and addObjectsFromArray but did find a solution to my problem.

What would be the fastest way to do this? How would you recommend to merge these two data structures?

Thank you!

Upvotes: 0

Views: 156

Answers (1)

stevesliva
stevesliva

Reputation: 5665

Assuming the dictionaries are named snapshot and refresh...

snapshot[@"Snapshot][@"bid"] = [snapshot[@"Snapshot][@"bid"] arrayByAddingObjectsFromArray:refresh[@"Refresh"][@"bid]];

More complicated union of the arrays will just require more code. And if you want price to be a unique key, why not make it a key?

Upvotes: 1

Related Questions