猿问

如何从属性中的键值对过滤对象数组

如果我在这个结构中有一些数据:


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 }

];

如何创建在其属性中具有特定键值对的新项目数组?例如,我想要一组由 Al Pacino 主演的电影,因此我需要过滤该数组以包含'Al Pacino': true在其属性中具有键值对的对象。此代码不起作用- 这只是我的最佳尝试。


const alPacinoFilms = topFilms.filter(function (film) {

  if(film.cast){

    return film.cast.includes({'Al Pacino': true});

  }

});

CodePen:https ://codepen.io/m-use/pen/ZEEjVOP


拉莫斯之舞
浏览 198回答 2
2回答

繁花如伊

首先,您不能将对象与 进行比较===,因为它们是不同的对象。其次,你想要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);

哈士奇WWW

你不能像那样过滤对象。您需要以某种方式遍历数组来检查它,而不是传入一个对象来获得匹配。您可以测试一个元素是否至少匹配使用Array.prototype.someconst alPacinoFilms = topFilms.filter(function (film) {  if(film.cast){    return film.cast.some(function(obj) { return obj['Al Pacino'] });  }});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答