Search code examples
javascriptfunctional-programmingramda.js

Use ramda to create nested object array from previous object array


I have Data like this:

[{fooId: '1', prop:'bla',prop2: 'bla', barId:'1', prop_1: 'bla', prop2_1: 'bla' },
{fooId: '1', prop:'bla',prop2: 'bla', barId:'2', prop_1: 'bla', prop2_1: 'bla' },
{fooId: '2', prop:'bla',prop2: 'bla', barId:'3', prop_1: 'bla', prop2_1: 'bla' },
{fooId: '2', prop:'bla',prop2: 'bla', barId:'4', prop_1: 'bla', prop2_1: 'bla' }]

and need to transform it like this using ramda:

[{fooId: '1', prop:'bla',prop2: 'bla', bars:[
{barId:'1', prop: 'bla', prop2: 'bla'},
{barId:'2', prop: 'bla', prop2: 'bla'}] },
{fooId: '2', prop:'bla',prop2: 'bla', bars:[
{barId:'3', prop: 'bla', prop2: 'bla'},
{barId:'4', prop: 'bla', prop2: 'bla'}] }
]

I used R.pick() to get a data structure like this however I got a new requirement and now properties need to be renamed. Using this reducer function I've got all Bars in every Foo instead of just the corresponding ones.

const transformQueryResult = r.pipe(
    r.groupBy(
        r.prop('fooId')
    ),
    r.map(r.reduce((enrichedFoo, fooWithBar) =>{
       enrichedFoo.fooId = fooWithBars.barId
       enrichedFoo.prop1 = fooWithBars.prop1
       enrichedFoo.prop2 = fooWithBars.prop2
       enrichedFoo.bars = r.append(
           {barId: fooWithBars.barId,
            prop1:fooWithBars.prop1_1,
            prop2:fooWithBars.prop2_1
           }, enrichedFoo.bars || []
      );
      return enrichedFoo;
    },{} )
),
r.values
)

Thanks in advance for every bit of help. I am new to functional programming and could solve this using loops in a minute but I am really struggling here right now.


Solution

  • Just found my solution. In case anybody wonders

        const transformData = r.pipe(
            r.groupBy(r.prop('fooId')),
            r.map((items) => {
                const { fooId, prop, prop2 } = items[0];
    
                const bars = r.map(item => ({
                    barId: item.barId,
                    prop: item.prop_1,
                    prop2: item.prop2_1
                }), items);
    
                return { fooId, prop, prop2, bars };
            }),
            r.values
        );