如何忽略Angular7中的对象字段



我如何告诉angular在http调用之前忽略一个或多个字段;像Java中的@JsonIgnore一样。

示例:

我有这个对象: {id: 1, libelle: 'test', mustIgnore: 'test'};

我希望这个对象为: {id: 1, libelle: 'test'};

我尝试了delete object.field,但是我正在寻找一种更简单的方法,例如在我的对象上使用注释。

,因为如果我有一系列对象,它将变得更加困难。

编辑:

我不想为每个对象手动执行此操作!是否有一种方法可以指定我要删除的字段,并且每当我有一个具有不同字段的对象以删除

时,就会自动执行此操作。

使用ES6 object destructuring获取无需属性的不变对象。

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);

如果您有数组,则可以简单地映射:

const ignoreArray = array
    .map(
        a => ({ id: a.id, libelle: a.libelle })
    )

结果,您只有idlibelle

编辑:根据Kunal的答案,更好的方法是:

const ignoreArray = array
    .map(
        obj => {
            const { mustIgnore1, mustIgnore2, ...rest } = obj;
            return rest
        }
    )

其中mustIgnore1mustIgnore2等。它们将是消除

的领域

如果您的数据集仅包含键 值组合,则可以创建一个新的空对象{},并循环遍历原始对象的所有成员,并检查每个键您想忽略一系列的关键名称。如果项目在数组中,请跳过它,如果不是,则将其添加到新对象中。

const array = [
{id: 1, libelle: 'test1', mustIgnore: 'ignore1'},
{id: 2, libelle: 'test2', mustIgnore: 'ignore2'},
{id: 3, libelle: 'test3', mustIgnore: 'ignore3'}
];
const newArray = [];
for (element of array) {
    const { mustIgnore, ...rest } = element;
    newArray.push(rest);
}
console.log(newArray);
 

另一种方式:

const array = [
{id: 1, libelle: 'test1', mustIgnore: 'ignore1'},
{id: 2, libelle: 'test2', mustIgnore: 'ignore2'},
{id: 3, libelle: 'test3', mustIgnore: 'ignore3'}
];
 const newArray = array.map(obj => {
                const { mustIgnore, ...rest } = obj;
                return rest;
 });
 console.log(newArray);

请查看object destructuring以获取进一步的参考,但这几乎是!

最新更新