0

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?

mhhabib
  • 2,975
  • 1
  • 15
  • 29
user3473406
  • 115
  • 1
  • 10
  • If the `"children"` list rarely changes, then it might be worth keeping a separate `"childrenQualifierId"` list. Then you only need to iterate over this list to find the `qualifierId`s. – quamrana Feb 03 '21 at 09:27
  • Thanks, unfortunately the children list will be unique for every object that this logic will be applied to – user3473406 Feb 03 '21 at 09:29
  • So, then the `"childrenQualifierId"` list will be unique. I'm just saying you *could* precompute this list and hold it alongside each `"children"` list. – quamrana Feb 03 '21 at 09:32

1 Answers1

1

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)
friedcell
  • 150
  • 6