gpt4 book ai didi

javascript - 如何根据数组内部数组的值过滤数组?

转载 作者:行者123 更新时间:2023-12-03 06:54:18 25 4
gpt4 key购买 nike

为什么这个测试没有通过?

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"}]}]);
});

最佳答案

因为 forEach 的返回值被完全忽略,并且您的 _.filter 谓词函数永远不会返回任何内容。

您可能想使用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 为数组中的每个条目调用谓词,在谓词第一次返回真值时停止;如果谓词返回真值,则其返回值为 true;如果没有返回,则返回值为 false

因此,我在上面强调的 return 是来自 _.filter 谓词的返回;您原来的 return true 是从 some (以前的 forEach)返回的。

关于javascript - 如何根据数组内部数组的值过滤数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37352380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com