我有2个像这样的阵列......
var heroes = [{
name: "Batman",
franchise: "DC"
},
{
name: "Ironman",
franchise: "Marvel"
},
{
name: "Thor",
franchise: "Marvel"
},
{
name: "Superman",
franchise: "DC"
}
];
var stars = ["Thor", "Superman"];
var marvelHeroes = heroes.filter(function(hero) {
return stars.indexOf(hero.name) >= 0;
});
console.log(marvelHeroes);
此代码返回'undefined'。所以基本上我试图根据另一个数组中的值过滤数组。
有人可以告诉我我做错了什么吗?感谢
我的预期输出是一系列对象,如下所示...
[
{name: "Thor", franchise: "Marvel"},
{name: "Superman", franchise: "DC"}
];
我见过类似问题here,但该解决方案对我不起作用......
答案 0 :(得分:1)
应该只返回 stars.indexOf(item.name) !== -1 ;
<强>样本强>
var heroes = [
{name: "Batman", franchise: "DC"},
{name: "Ironman", franchise: "Marvel"},
{name: "Thor", franchise: "Marvel"},
{name: "Superman", franchise: "DC"}
];
var stars = ["Thor","Superman"];
var filtered = heroes.filter(function(item) {
return stars .indexOf(item.name) !== -1 ;
});
console.log(filtered);
&#13;
答案 1 :(得分:0)
您可以使用includes
来确定数组是否包含某个元素
var heroes = [{name:"Batman",franchise:"DC"},{name:"Ironman",franchise:"Marvel"},{name:"Thor",franchise:"Marvel"},{name:"Superman",franchise:"DC"}];
var stars = ["Thor", "Superman"];
var marvelHeroes = heroes.filter(function(hero) {
return stars.includes(hero.name);
});
console.log(marvelHeroes);
&#13;
更短的代码:
var heroes = [{name:"Batman",franchise:"DC"},{name:"Ironman",franchise:"Marvel"},{name:"Thor",franchise:"Marvel"},{name:"Superman",franchise:"DC"}]
var stars = ["Thor", "Superman"];
var marvelHeroes = heroes.filter(o => stars.includes(o.name));
console.log( marvelHeroes );
&#13;
Doc:includes()