我得到一个json响应并将其存储在mongodb中,但是我不需要的字段也会进入数据库,无论如何都要删除那些无用的字段?
interface Test{
name:string
};
const temp :Test = JSON.parse('{ "name":"someName","age":20 }') as Test;
console.log(temp);
输出:
{ name: 'someName', age: 20 }
答案 0 :(得分:6)
您可以使用从给定对象中选择某些属性的函数:
<main>
<div id="wrapper">
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li>
<span style="height:50px" />
</li>
<li class="dropdown" id="mi1">
<a class="menu-toggle" href="#" class="dropdown-toggle" data-toggle="dropdown">Service Provision<span class="fa fa-chevron-down pull-right sideMenuChevrons"></span></a>
<ul class="sideDropDown dropdown-menu" role="menu">
<li><a href="#">Service Provision<span class="fa fa-external-link pull-right newTabIcon" onclick="window.open('#')"></span></a></li>
<li><a href="#">Automation Requests<span class="fa fa-external-link pull-right newTabIcon" onclick="window.open('#')"></span></a></li>
</ul>
</li>
<li class="dropdown">
<a class="menu-toggle" href="#" class="dropdown-toggle" data-toggle="dropdown">NMC<span class="fa fa-chevron-down pull-right sideMenuChevrons"></span></a>
<ul class="sideDropDown dropdown-menu" role="menu">
<li><a href="#">Customers<span class="fa fa-external-link pull-right newTabIcon" onclick="window.open('#')"></span></a></li>
<li><a href="#">Contractors<span class="fa fa-external-link pull-right newTabIcon" onclick="window.open('#')"></span></a></li>
<li><a href="#">Suppliers<span class="fa fa-external-link pull-right newTabIcon" onclick="window.open('#')"></span></a></li>
</ul>
</li>
<li class="dropdown">
<a class="menu-toggle" href="#" class="dropdown-toggle" data-toggle="dropdown">Site Access<span class="fa fa-chevron-down pull-right sideMenuChevrons"></span></a>
<ul class="sideDropDown dropdown-menu" role="menu">
<li><a href="#">Site Access<span class="fa fa-external-link pull-right newTabIcon" onclick="window.open('#')"></span></a></li>
<li><a href="#">Key Issue<span class="fa fa-external-link pull-right newTabIcon" onclick="window.open('#')"></span></a></li>
</ul>
</ul>
<div class="dropup">
<a id="menu-toggle-reversed" href="#" class="dropdown-toggle dropup" data-toggle="dropdown"><i id="adminIconPadding" class="fa fa-user-md"></i>Admin<span class="fa fa-chevron-up pull-right sideMenuChevronsDropUp"></span></a>
<ul id="adminDropup" class="dropdown-menu" role="menu">
<li><a href="#">Settings<span class="fa fa-external-link pull-right newTabIcon" onclick="window.open('#')"></span></a></li>
</ul>
</div>
</div>
然后:
function pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {
const copy = {} as Pick<T, K>;
keys.forEach(key => copy[key] = obj[key]);
return copy;
}
答案 1 :(得分:1)
假设您要删除年龄
temp = {...temp, age: undefined}
这将从您的对象中删除age
。
答案 2 :(得分:0)
由于接口在运行时不存在,因此接口不会影响运行时行为。您必须使用delete
let obj = JSON.parse('{ "name":"someName","age":20 }')
delete obj.age;
答案 3 :(得分:0)
如果要以强类型方式执行此操作,则可以定义一个满足您的界面(const dummy: IMyInterface = {someField: "someVal"};
)的虚拟/理想对象,然后根据Object.keys(dummy)
过滤传入对象的字段。这样,如果您在不更新此“过滤”代码的情况下更新接口,则编译器将抱怨。