I have below object -
[
{
employeeId:1
employeeName:"ABC"
},
{
employeeId:2
employeeName:"ABD"
},
{
employeeId:3
employeeName:"FEW"
},
{
employeeId:4
employeeName:"JKABL"
},]
I want to filter this list as per word provided on employeeName.
Eg. If employee name word provided :- AB ; then it should filter out -
[
{
employeeId:1
employeeName:"ABC"
},
{
employeeId:2
employeeName:"ABD"
},
{
employeeId:4
employeeName:"JKABL"
},]
As EmployeeIds 1,2 and 4 contains employeename with AB.
For this I tried -
object.filter(x=>x.employeeName.indexOf("AB")>-1)
This is returning empty array every time.
Second way I tried -
var filteredObject=object.map(x=>{
if(x.employeeName.indexOf("AB")>-1)
return x;
});
This is returning undefined every time.
CodePudding user response:
You can define a custom function which filter using 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'));
CodePudding user response:
I tried this apporach.
let arr = [
{
employeeId:1,
employeeName:"ABC"
},
{
employeeId:2,
employeeName:"ABD"
},
{
employeeId:3,
employeeName:"FEW"
},
{
employeeId:4,
employeeName:"JKABL"
},];
let res = arr.filter((item) => item.employeeName.includes("AB"));
console.log(res);
OUTPUT :
[
{ employeeId: 1, employeeName: 'ABC' },
{ employeeId: 2, employeeName: 'ABD' },
{ employeeId: 4, employeeName: 'JKABL' }
]