0

lodash _.findWhere (_.where と同じ) を使用すると、何かが追加されます。

var testdata = [
    {
        "id": "test1",
        "arr": [{ "a" : "a" }]
    },
    {
        "id": "test2",
        "arr": []
    }
];

_.findWhere(testdata, {arr : [] });
//--> both elements are found

arr が空の配列である testdata から要素を抽出しようとしていますが、 _.where には空でない配列の要素も含まれています。

私も _.matchesProperty でテストしましたが、同じ結果はありません。

私は何か簡単なものを見逃していると確信していますが、何が見えません:s

助けてください :)

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

4

1 に答える 1

2

このために、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' } ] } ]
于 2015-02-25T18:58:37.373 に答える