json - 如何在 Angular7 中忽略对象字段
如何告诉 Angular 在进行 HTTP 调用之前忽略一个或多个字段;就像 Java 中的 @JsonIgnore 一样。
示例:
我有这个对象:{id: 1, libelle: 'test', mustIgnore: 'test'};
我期望这个对象是:{id: 1, libelle: 'test'};
我尝试了 delete object.field,但我在寻找一种更简单的方法来做到这一点,比如在我的对象上使用注解。
因为如果我有一个对象数组,管理起来会变得更困难。
编辑 :
我不想对每个对象手动操作!有没有办法只指定我想删除的字段,并且每当我有不同的对象需要删除不同的字段时自动执行
答案#1
使用 ES6 对象解构 来获取一个不包含所需属性的不可变对象。
const obj = {id: 1, libelle: 'test', mustIgnore: 'test'};
// Destructure into mustIgnore and rest properties
const { mustIgnore, ...rest } = obj;
const projectedObject = rest;
console.log("old", obj);
console.log("new", projectedObject);答案#2
如果你有一个数组,你可以简单地映射如下:
const ignoreArray = array
.map(
a => ({ id: a.id, libelle: a.libelle })
)
因此,你将得到一个仅包含 id 和 libelle 的对象数组。
编辑:根据库纳尔的回答,更好的方法是:
const ignoreArray = array
.map(
obj => {
const { mustIgnore1, mustIgnore2, ...rest } = obj;
return rest
}
)
其中 mustIgnore1、mustIgnore2 等。这些将是要消除的字段
