I am defined the MenuItem
like this to parse the server side rest api response:
type MenuItem = {
id: number;
name: string;
path: string;
tree_id_path: string;
children: MenuItem[];
};
the server side return more than 4 fields, but I only want the MenuItem
to take 4 fields. what should I do to make it work like this? Now I am using as to cast the reponse to MenuItem
list.
export async function roleMenuTree(options?: { [key: string]: any }) {
let response = await request<API.ApiResponse>('/manage/permission/role/v1/role/menu', {
method: 'POST',
body: JSON.stringify({}),
...(options || {}),
});
let dataList = response.result as API.MenuItem[];
return dataList;
}
CodePudding user response:
You can easily achieve this using es6.
By using the Spread syntax
let { unWantedFields ,...rest} = response.result;
let result = rest
Or you can use Destructuring assignment to include your desire props
let {id, name, path} = response.result;
let result = {id, name, path}
CodePudding user response:
As an alternative you can return a new object
export async function roleMenuTree(options?: { [key: string]: any }) {
let response = await request<API.ApiResponse>('/manage/permission/role/v1/role/menu', {
method: 'POST',
body: JSON.stringify({}),
...(options || {}),
});
let newResult: MenuItem = {
id: response?.result?.id,
name: response?.result?.name,
path: response?.result?.path,
tree_id_path: response?.result?.tree_id_path,
children: //Here your MenuItem[]
}
let dataList = newResult;
return dataList;
}
Or you can use this approach (If you have same names in api response as well)
let {id, name, path, tree_id_path, children} = response.result;