map funkce
je pro pole, takže budu předpokládat vaše products klíč ve vašem příkladu je pole, nikoli objekt.
Nejprve bych vám doporučil správně napsat definice typů pro vaše produkty, pokud jste tak již neučinili
interface IProduct {
_id: string,
category: number,
gender: number,
title: string,
description: string,
price: number,
imageFileName: string,
createdAt: string,
updatedAt: string,
__v: number
}
interface IResponse {
_id: string;
products: IProduct[];
}
Poté získáte možnost Pick práce na jediném product objekt, můžete indexovat IResponse rozhraní pomocí Indexované typy přístupu
. Chcete products vlastnost na index protože je to pole.
/*
Indexed Access Types
type Person = { age: number, name: string }[];
type Age = Person[number]["age"];
*/
type Products = ReadonlyArray<
Pick<
IResponse["products"][number],
"_id" | "gender" | "title" | "description" | "price" | "imageFileName"
>
>;
Pokud byste udělali něco jako Pick<IResponse["products"], '_id'...> budete se snažit použít Pick extrahovat vlastnosti z pole, což by vedlo k chybě.
A jediné, co zbývá, je namapovat produkty z odezvy na požadovaný tvar objektu.
// Query your products
const { products }: IResponse = {
_id: "611e2febb863ce74ac448220",
products: [
{
_id: "6116a9ecc3e98d500c5e523d",
category: 5,
gender: 1,
title: 'sivdosi',
description: 'oisbdvoi',
price: 2394,
imageFileName: 'https://localhost:3000/images/1628875244435-3564.png',
createdAt: "2021-08-13T17:20:44.472Z",
updatedAt: "2021-08-13T17:20:44.472Z",
__v: 0
}
]
}
// Get the desired object
const pickedProducts: Products = products.map(({ _id, gender, title, description, price, imageFileName }) => ({
_id,
gender,
title,
description,
price,
imageFileName
}));
Konečný výsledek vypadá asi takto
interface IProduct {
_id: string,
category: number,
gender: number,
title: string,
description: string,
price: number,
imageFileName: string,
createdAt: string,
updatedAt: string,
__v: number
}
interface IResponse {
_id: string;
products: IProduct[];
}
type Products = ReadonlyArray<
Pick<
IResponse["products"][number],
"_id" | "gender" | "title" | "description" | "price" | "imageFileName"
>
>;
// Query your products
const { products }: IResponse = {
_id: "611e2febb863ce74ac448220",
products: [
{
_id: "6116a9ecc3e98d500c5e523d",
category: 5,
gender: 1,
title: 'sivdosi',
description: 'oisbdvoi',
price: 2394,
imageFileName: 'https://localhost:3000/images/1628875244435-3564.png',
createdAt: "2021-08-13T17:20:44.472Z",
updatedAt: "2021-08-13T17:20:44.472Z",
__v: 0
}
]
}
// Get the desired object
const pickedProducts: Products = products.map(({ _id, gender, title, description, price, imageFileName }) => ({
_id,
gender,
title,
description,
price,
imageFileName
}));