I have data that looks likem that is of type IconItems:
{
title: "Category title",
description: "Example description",
lists: [
{
id: "popular",
title: "Popular",
items: [
{
id: 1,
title: "title",
provider: "provider",
image: ""
},
....
]
},
{
id: "new",
title: "New",
items: [
{
id: 4,
title: "studioss2",
provider: "provider",
image: ""
},
....
]
}
I want to filter the nestled items (type IconItem, in singular) array based on a string value.
For this I have defined these two values:
const filterKeyOpt: Array<keyof IconItem> = ["title", "provider", "image"];
const searchQuery = 'sTudioSS'
I try to filter out the data
const logData = () => {
let filteredData = data?.lists.map((item) => item.items.filter((i) => {
return filterKeyOpt.some((key) => i[key].toString().toLowerCase().includes(searchQuery.toLowerCase()))
} /// returns IconItem[][] | undefined but I want to return type IIconItems | undefined
))
console.log(filteredData)
}
But the output is of type
IconItem[][]
But I want the full thing/type. Ie. filter out on a nestled value and give back a copy of the data object, with matching properties. How to do that?
CodePudding user response:
const logData = () => {
let a: typeof data = {
...data,
lists: data.lists.map(list => {
// ^?
return { // only matching items
...list,
items: list.items.filter(item => {
// ^?
filterKeyOpt.some((key) => item[key].toString().toLowerCase().includes(searchQuery.toLowerCase()))
})
}
}).filter(list => {
// only non-empty lists
return list.items.length
})
}
return a.lists.length ? a : undefined;
}