javascriptimmutable.jsimmutablelist

Push element to an immutable List without reassigning variable


How to avoid reassign of variables while iterating over an immutable List, to create another one. I have the code below, which is working fine,

function foobar(stateValue) {
let propsValue = List();
stateValue.forEach((categoryItem) => {
    categoryItem.get('coveragePayorIds', List()).forEach((
        coveragePayorId) => {
        const category = categoryItem.get('category');
        propsValue = propsValue.push({
        category,
        coverage_payor_id: coveragePayorId,
        });
    });
});
return propsValue;
}

I'm trying to make the propsValue a const. How it can be achieved?


Solution

  • forEach is all about side effects and doesn't work with immutable structures or variables. Don't use it.

    function foobar(stateValue) {
        return List(stateValue).flatMap(categoryItem => {
            const category = categoryItem.get('category');
            return categoryItem.get('coveragePayorIds', List()).map(coverage_payor_id =>
                ({category, coverage_payor_id})
            );
        });
    }