I have an array of object and inside every array i have list of users, when i search i should be able to search the users and return value without effecting the existing structure. stackblitz
I have tried but its not working have shared the stackblitz link where I have done
userList = [
{ state: 'KL', level: 1, USERS: ['jane', 'kete'] },
{ state: 'TN', level: 1, USERS: ['john', 'rock'] },
{ state: 'MH', level: 2, USERS: ['rahul', 'ricky'] },
{ state: 'AP', level: 2, USERS: ['ram', 'sham'] },
];
handleSearch(kete) // search us an input field detailed in stackblitz link
handleSearch = (e) => {
this.userList = this.orgList;
const user = this.searchFunction(this.userList, e.target.value);
console.log(user);
};
// search function
searchFunction = (arr, searchVal) => {
return arr.map((item) => {
console.log(item);
const data = item.USERS.filter((user) =>
user.toLowerCase()?.includes(searchVal?.toLowerCase())
);
return { ...item, data };
});
};
CodePudding user response:
As you are returning data in an object through { ...item, data }, the retains all it's fields and adds a new field called data with filtered users.
Instead what you want to do is replace the list of USERS in the current item object.
searchFunction = (arr, searchVal) => {
return arr.map((item) => {
const data = item.USERS.filter((user) =>
user.toLowerCase()?.includes(searchVal?.toLowerCase())
);
return { ...item, USERS: data };
});
};
CodePudding user response:
You could use filter() and includes() to filter out the objects where the username is in the USERS array of the object.
const userList = [
{ state: 'KL', level: 1, USERS: ['jane', 'kete'] },
{ state: 'TN', level: 1, USERS: ['john', 'rock'] },
{ state: 'MH', level: 2, USERS: ['rahul', 'ricky'] },
{ state: 'AP', level: 2, USERS: ['ram', 'sham'] },
];
const findUser = (username, users) => {
return users.filter(u => u.USERS.includes(username));
}
console.log(findUser("rahul", userList));
CodePudding user response:
Check this solution: https://stackblitz.com/edit/angular-w1vi9e Basicly, we make an array of users, and on each value of search input change, we search the array of users for any user whose name contains the search value and we're showing their names for testing purposes.
