Search code examples
javascriptlodash

Lodash. How filter object of objects?


There object of carts with items.

carts: {
                0: {
                    id:1,
                    items:{
                        0:{id:100},
                        1:{id:101},
                        2:{id:10}
                    }
                },
                1: {
                    id:2,
                    items:{
                        0:{id:34},
                        1:{id:15},
                        2:{id:46}
                    }
                },
            }

Also i have simple array with items id [101, 46] to remove from first array.

How filter my object by lodash?


Solution

  • Similar solution to what Jonas proposed but with plain ES5, Lodash and without mutations:

    var carts = {
        // ...
    };
    
    function getFilteredCarts(carts, idsToRemove) {
        return _.mapValues(carts, function (value) {
            return _.omitBy(value.items, function (item) {
                return _.includes(idsToRemove, item.id);
            });
        });
    }
    
    getFilteredCarts(carts, [101, 46]);
    

    Try it