Why doesn't this test pass?
it('lodash_test', function() {
var arr = [{a: "x", b: [{x: "1", y: "2"}]}, {a: "x", b: [{x: "1", y: "2"}]}, {a: "x", b: [{x: "33", y: "2"}]}]
var result = _.filter(arr, function(obj) {
obj.b.forEach(function(item_b) {
if(item_b.x=="1") {
return true;
}
});
});
expect(result).to.be.eql([{a: "x", b: [{x: "1", y: "2"}]}, {a: "x", b: [{x: "1", y: "2"}]}]);
});
Because forEach
's return value is completely ignored, and your _.filter
predicate function never returns anything.
You probably wanted to use some
:
it('lodash_test', function() {
var arr = [{a: "x", b: [{x: "1", y: "2"}]}, {a: "x", b: [{x: "1", y: "2"}]}, {a: "x", b: [{x: "33", y: "2"}]}]
var result = _.filter(arr, function(obj) {
return obj.b.some(function(item_b) {
// ^^^^^^^ ^^^^
if(item_b.x=="1") {
return true;
}
});
});
expect(result).to.be.eql([{a: "x", b: [{x: "1", y: "2"}]}, {a: "x", b: [{x: "1", y: "2"}]}]);
});
Array#some
calls the predicate for each entry in the array, stopping the first time the predicate returns a truthy value; its return value is true
if the predicate ever returned a truthy value, or false
if not.
So the return
I've underscored in the above is the return from the _.filter
predicate; your original return true
is the return from some
(formerly forEach
).
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加