简体   繁体   English

Lodash。 如何过滤对象的对象?

[英]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. 我也有简单的数组,其ID为[101,46]的项目要从第一个数组中删除。

How filter my object by lodash? 如何通过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: 与Jonas提出的解决方案类似的解决方案,但具有普通的ES5,Lodash且无突变:

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 试试吧

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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