Search code examples
pythonlodashpydash

How to map element of an array using pyDash in Python


I'm trying to chain and group than map an array using pydash

The idea is to recreate the same output of this lodash function :

let chainedResult = (
    _.chain(oResult)
    // Group the elements of the result based on `CEMPLOYEE` property
    .groupBy("CCALENDAR_WEEK")
    // `key` is group's name (CEMPLOYEE), `value` is the array of objects
    .map((value, key) => ({
        WEEK: key,
        Capacity: value
    }))
).value();

So far, this is what I achieved

_.chain(empCapacity).group_by(lambda dt:dt["CCALENDAR_WEEK"]).value()

I'm stuck here, on how to make the mapping of the keys and value? How to do the below code in python using pydash?

    .map((value, key) => ({
        WEEK: key,
        Capacity: value
    }))

Desired Output :

enter image description here


Solution

  • Did you try just using .map()? The docs say:

    The iteratee is invoked with three arguments: (value, index|key, collection).

    Because that seems to be copied straight from the lodash docs. In python it's smart enough to check the signature of the "iteratee" (i.e. the function you pass to .map()), otherwise this would crash since in python you can't pass extra arguments to a function that is not expecting them.

    So this works for me:

    from pydash import py_
    
    my_entries = [
        {'name': 'barney', 'food': 'jelly'},
        {'name': 'bill', 'food': 'jelly'},
        {'name': 'buster', 'food': 'aubergine'},
    ]
    
    (
        py_(my_entries)
        .group_by('food')
        .map(lambda value, key: (key, value))
    ).value()
    

    Gives:

    [
        (
            'jelly',
            [
                {'name': 'barney', 'food': 'jelly'}, 
                {'name': 'bill', 'food': 'jelly'},
            ]
        ),
        (
            'aubergine', 
            [
                {'name': 'buster', 'food': 'aubergine'}
            ]
        )
    ]