如何在数组myArray
中的title
中包含单词“ wish ”的所有元素中查找。为此,我想使用 Lodash 或香草 JavaScript 。
const myArray = [
{
id:1,
category:"HappyBirthday",
title:"Best wishes"
},
{
id:2,
category:"HappyBirthday",
title:"Happy Birthday"
},
{
id:3,
category:"TopPerformer",
title:"Good job - Girl"
},
{
id:4,
category:"TopPerformer",
title:"Wish you continued success"
},
{
id:5,
category:"WorkAnniversary",
title:"Happy work anniversary"
}
];
预期结果:
const searchResults = [
{
id:1,
category:"HappyBirthday",
title:"Best wishes"
},
{
id:4,
category:"TopPerformer",
title:"Wish you continued success"
}
];
答案 0 :(得分:3)
const myArray = [
{
id:1,
category:"HappyBirthday",
title:"Best wishes"
},
{
id:2,
category:"HappyBirthday",
title:"Happy Birthday"
},
{
id:3,
category:"TopPerformer",
title:"Good job - Girl"
},
{
id:4,
category:"TopPerformer",
title:"Wish you continued success"
},
{
id:5,
category:"WorkAnniversary",
title:"Happy work anniversary"
}
];
const filtered = myArray.filter(obj => obj.title.toLowerCase().includes("wish"));
console.log(filtered);
或者您可以简单地做到这一点:
myArray.filter(item => item.title.match(/wish/i));
在这里,我正在使用正则表达式并检查标题是否包含单词wish
。 i
告诉引擎忽略大小写。
答案 1 :(得分:1)
您可以为此使用正则表达式。
const retval = myArray.filter(x => x.title.match(/wish/i));
重要
如果要跳过过滤器中的区分大小写,那么将其包括进来真的很重要
/i
答案 2 :(得分:0)
带有Array.prototype.filter
的简单RegExp.prototype.test
应该可以完成这项工作:
const myArray=[{id:1,category:"HappyBirthday",title:"Best wishes"},{id:2,category:"HappyBirthday",title:"Happy Birthday"},{id:3,category:"TopPerformer",title:"Good job - Girl"},{id:4,category:"TopPerformer",title:"Wish you continued success"},{id:5,category:"WorkAnniversary",title:"Happy work anniversary"}]
const filtered = myArray.filter(({title}) => /wish/gi.test(title));
console.log(filtered);