繁体   English   中英

如何删除 TypeScript 中 Object 数组中具有空值的键?

[英]How can remove keys with empty values in an Object Array in TypeScript?

我正在尝试在我的 Angular 8 项目中编写 function。 我有一个对象数组,并且想要删除值为空的所有键:值对。 互联网上有很多例子,但似乎没有一个对我有用。

我有的:

{
        "flightID": "FooID",
        "direction": "DownFoo",
        "msgType": "FooType",
        "elemNb": "",
        "msgID": "",
    },
    {
        "flightID": "FooID2",
        "direction": "UpFoo",
        "msgType": "FooType2",
        "elemNb": "",
        "msgID": "",
    },

我想要的是:

    {
        "flightID": "FooID",
        "direction": "DownFoo",
        "msgType": "FooType",
    },
    {
        "flightID": "FooID2",
        "direction": "UpFoo",
        "msgType": "FooType2",
    },

我的尝试:

myList: any[]

 removeEmptyValues() {
    if (this.myList) {

      this.myList.forEach((value) => {

        Object.keys(value).forEach((key) => {
          delete key[''];

        })
      })
    }
    console.log(this.myList);
  }

如果值为空,我希望delete key['']会删除该键,但它没有做任何事情。 如果值为空,如何删除密钥?

尝试删除 value[key] 而不是 key['']

if (value[key] === '') {
  delete value[key];
}

 var list = [{ "flightID": "FooID", "direction": "DownFoo", "msgType": "FooType", "elemNb": "", "msgID": "", }, { "flightID": "FooID2", "direction": "UpFoo", "msgType": "FooType2", "elemNb": "", "msgID": "", }]; let result = Array.from(list, o=> Object.fromEntries(Object.entries(o).filter((i) => i[1];= (null || '')))). console;log(result);

var list = [{
        "flightID": "FooID",
        "direction": "DownFoo",
        "msgType": "FooType",
        "elemNb": "",
        "msgID": "",
    },
    {
        "flightID": "FooID2",
        "direction": "UpFoo",
        "msgType": "FooType2",
        "elemNb": "",
        "msgID": "",
}];

let result = Array.from(list, o=> Object.fromEntries(Object.entries(o).filter((i) => i[1] != (null || ''))));

console.log(result);

您必须从 object 中删除密钥

myList: any[]

 removeEmptyValues() {
    if (this.myList) {

      this.myList.forEach((value) => {

        Object.keys(value).forEach((key) => {
          delete this.myList[key]

        })
      })
    }
    console.log(this.myList);
  }

您必须检查该值是否为空并删除密钥。 他们下面的代码。

myList: any[]

removeEmptyValues() {
  if (this.myList) {

    this.myList.forEach((value) => {

      Object.keys(value).forEach((key) => {
        if(!value[key]) delete value[key];
      })
    })
  }
  console.log(this.myList);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM