gpt4 book ai didi

Javascript : Filter list with element contains

转载 作者:行者123 更新时间:2023-12-05 01:50:38 29 4
gpt4 key购买 nike

我有以下对象-

[
{
employeeId:1
employeeName:"ABC"
},
{
employeeId:2
employeeName:"ABD"
},
{
employeeId:3
employeeName:"FEW"
},
{
employeeId:4
employeeName:"JKABL"
},]

我想根据 employeeName 上提供的单词过滤此列表。

例如。如果提供员工姓名单词:- AB;然后它应该过滤掉-

[
{
employeeId:1
employeeName:"ABC"
},
{
employeeId:2
employeeName:"ABD"
},
{
employeeId:4
employeeName:"JKABL"
},]

因为 EmployeeIds 1,2 和 4 包含带 AB 的员工姓名。

为此我尝试了-

object.filter(x=>x.employeeName.indexOf("AB")>-1)

每次都返回空数组。

我试过的第二种方法-

   var filteredObject=object.map(x=>{
if(x.employeeName.indexOf("AB")>-1)
return x;
});

每次都返回 undefined。

最佳答案

您可以定义一个自定义函数,该函数使用 includes 进行过滤:

const data = [
{
employeeId: 1,
employeeName: 'ABC',
},
{
employeeId: 2,
employeeName: 'ABD',
},
{
employeeId: 3,
employeeName: 'FEW',
},
{
employeeId: 4,
employeeName: 'JKABL',
},
];

const filterName = (search) => {
return data.filter((value) => value.employeeName.includes(search));
};

console.log(filterName('AB'));

关于Javascript : Filter list with element contains,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72908011/

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