为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

拉莫斯之舞 2021-12-23 19:52:39
如果我在这个结构中有一些数据: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
查看完整描述

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);


查看完整回答
反对 回复 2021-12-23
?
哈士奇WWW

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

  }

});


查看完整回答
反对 回复 2021-12-23
  • 2 回答
  • 0 关注
  • 197 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号