lodash用空数组查找where



我在使用lodash _.findWhere(与_.where相同)时遇到了一些问题

var testdata = [
    {
        "id": "test1",
        "arr": [{ "a" : "a" }]
    },
    {
        "id": "test2",
        "arr": []
    }
];
_.findWhere(testdata, {arr : [] });
//--> both elements are found

我试图从测试数据中提取元素,其中arr是一个空数组,但_.where也包括具有非空数组的元素。

我也用_.matchesProperty进行了测试,但不可能,结果是一样的。

我确信我错过了一些简单的东西,但看不到

请帮忙:)

http://plnkr.co/edit/DvmcsY0RFpccN2dEZtKn?p=preview

为此,您需要isEmpty():

var collection = [
    { id: 'test1', arr: [ { a : 'a' } ] },
    { id: 'test2', arr: [] }
];
_.find(collection, function(item) {
    return _.isEmpty(item.arr);
});
// → { id: 'test2', arr: [] }
_.reject(collection, function(item) {
    return _.isEmpty(item.arr);
});
// → [ { id: 'test1', arr: [ { a : 'a' } ] } ]

您还可以使用更高阶的函数,如flow(),因此可以抽象您的回调:

var emptyArray = _.flow(_.property('arr'), _.isEmpty),
    filledArray = _.negate(emptyArray);
_.filter(collection, emptyArray);
// → [ { id: 'test2', arr: [] } ]
_.filter(collection, filledArray);
// → [ { id: 'test1', arr: [ { a : 'a' } ] } ]

最新更新