Search code examples
pythonarraysiterationdesign-decisions

Making conditional decision based on objects in an Array


I currently have an object which contains an array of other objects

{
    "id": 2247511687,
    "timeStamp": "2020-12-20T19:51:32.275Z",
    "children": [
        {
            "id": 2662773967,
            "qualifierId": 33
        },
        {
            "id": 2662774089,
            "qualifierId": 343,
            "value": "3"
        },
        {
            "id": 2662773969,
            "qualifierId": 245
        }
    ]
}

I need to make decisions on what to do with the Object is based on the child array. Using the example above if qualified 343 and 245 are present in the object I want to do X with the object, however, if only qualified 343 is present I want to do Y with the object.

Is there an efficient way to do this without multiple iterations of the object? Or a format to convert the data to that has easier accessibility?


Solution

  • Define processor functions before doing the iteration, while iterating pick the one that is needed and run the operation.

    Assuming l is a list of objects d you specified, you could use something like:

    def fn1(o): return (1, o)
    
    def fn2(o): return (2, o)
    
    def whichfn(qids):
        if 343 in qids and 245 in qids:
            return fn1
        elif 343 in qids:
            return fn2
    
    for d in l:
        # get all qualifierIds into a set
        qids = {v.get("qualifierId") for v in d["children"]}
    
        # find the function you need
        fn = whichfn(qids)
    
        # run the function
        if fn:
            fn(d)