如何在Angular7中忽略对象字段

时间:2019-06-24 15:30:07

标签: json angular typescript angular7

如何在http调用之前告诉Angular忽略一个或多个字段;就像Java中的var content = ''; firebase.database().ref().child("Users").on('value', function (snapshot) { if (snapshot.exists()) { //console.log(snapshot.key) content = '<ul>'; snapshot .sort((a, b) => b.Usuario-a.Usuario) .forEach(function (data) { var val = data.val(); content += '<li>' + val.Usuario + '</li>'; }); content += '</ul>'; $("#A_Usuarios").append(content); } });

示例:

我有这个对象:@JsonIgnore;

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

我尝试了{id: 1, libelle: 'test'},但是我正在寻找一种更简单的方法,例如在对象上使用注释。

由于我有一个对象数组,因此管理起来变得更加困难。

编辑:

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

4 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:3)

如果有数组,则可以像这样简单映射:

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等处。它们将是要消除的字段

答案 2 :(得分:1)

如果数据集仅包含键和值的组合,则可以创建一个新的空对象{}并使用for循环遍历原始对象的所有成员,并使用所需的键名数组检查每个键忽视。如果该项在数组中,请跳过它;如果不是,则将其添加到新对象中。

答案 3 :(得分:1)

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以获得更多参考,但这差不多!