2 回答

TA贡献2012条经验 获得超12个赞
首先,您不能将对象与 进行比较===,因为它们是不同的对象。
其次,你想要some而不是includes当你有其他东西而不是为了完全平等进行比较。
最后,考虑让您的强制转换字段只是字符串数组,而不是具有真/假值的对象。
const topFilms = [
{ title: 'The Shawshank Redemption', year: 1994, cast: [{'Al Pacino': false}, {'Morgan Freeman': true}] },
{ title: 'The Godfather', year: 1972, cast: [{'Marlon Brando': true}, {'Al Pacino': true}] },
{ title: 'The Godfather: Part II', year: 1974, cast: [{'Al Pacino': true}, {'Robert De Niro': true}] },
{ title: 'The Dark Knight', year: 2008 }
];
let alPacinoFilms = topFilms.filter(film => film.cast && film.cast.some(castMember => castMember['Al Pacino']));
console.log(alPacinoFilms);

TA贡献1799条经验 获得超6个赞
你不能像那样过滤对象。您需要以某种方式遍历数组来检查它,而不是传入一个对象来获得匹配。您可以测试一个元素是否至少匹配使用Array.prototype.some
const alPacinoFilms = topFilms.filter(function (film) {
if(film.cast){
return film.cast.some(function(obj) { return obj['Al Pacino'] });
}
});
添加回答
举报