我正在尝试在Angular 8项目中编写一个函数。我有一个对象数组,想要删除其中值为空的所有key:value对。互联网上有很多例子,但似乎没有一个适合我。
我所拥有的:
{
"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['']
将删除键,如果该值为空,但它没有做任何事情。如果值为空,如何删除密钥?
答案 0 :(得分:2)
尝试删除value [key]而不是key ['']
if (value[key] === '') {
delete value[key];
}
答案 1 :(得分:1)
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);
答案 2 :(得分:0)
您必须从对象中删除密钥
myList: any[]
removeEmptyValues() {
if (this.myList) {
this.myList.forEach((value) => {
Object.keys(value).forEach((key) => {
delete this.myList[key]
})
})
}
console.log(this.myList);
}
答案 3 :(得分:0)
您必须检查该值是否为空,然后删除键。他们下面的代码。
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);
}