gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 14:13:13 26 4
gpt4 key购买 nike

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

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

代码笔:https://codepen.io/m-use/pen/ZEEjVOP

最佳答案

  • 首先,您不能将对象与 === 进行比较,因为它们是不同的对象。

  • 其次,当您除了比较完全相等之外还有其他内容时,您需要 some 而不是 includes

  • 最后,请考虑让您的转换字段只是字符串数组,而不是具有 true/false 值的对象。

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

关于javascript - 如何从属性中的键值对过滤对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58809482/

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