简体   繁体   中英

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?

Object.values(carts).forEach(({items}) => {
  for(var i in items)
    if(ids.includes(items[i].id)) delete items[i];
});

Try it

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM