gpt4 book ai didi

javascript - 如果javascript中所有值都为空,如何删除对象?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:11:09 25 4
gpt4 key购买 nike

我在数组中有多个对象。它在对象中具有带有 value 属性的 values 数组。当所有值属性都为空时。我想删除整个对象。

我试过了,但我无法产生输出。请帮助我。

var data = [
{
"field": "surname",
"values": [
{
"id": "drivingLicenseFront",
"value": "",
"isAvailable": true
},
{
"id": "passport",
"value": "",
"isAvailable": true
}
],
"status": "passed"
},
{
"field": "given names",
"values": [
{
"id": "drivingLicenseFront",
"value": "",
"isAvailable": true
},
{
"id": "passport",
"value": "",
"isAvailable": true
}
],
"status": "passed"
},
{
"field": "date of birth",
"values": [
{
"id": "drivingLicenseFront",
"value": "25.07.1974",
"isAvailable": true
},
{
"id": "passport",
"value": "05 JUN /JOIN 57",
"isAvailable": true
}
],
"status": "passed"
}
];

for (let x = data.length-1; x >= 0; x--) {
let count = 1;
var dataValueLength = data[x].values.length;
for (let y = 0; y < data[x].values.length; y++) {
if (data[x].values[y].value === "") {
count++;
}
}
if (dataValueLength == count) {
data.splice(x, 1)
}
}

console.log(JSON.stringify(data));

在上面的场景中,输出应该只有一个对象,即“出生日期”。

最佳答案

非常接近,只有一个问题(您正在将 count 初始化为 1 而不是 0),使它

let count = 0;

演示

var data = [{
"field": "surname",
"values": [{
"id": "drivingLicenseFront",
"value": "",
"isAvailable": true
},
{
"id": "passport",
"value": "",
"isAvailable": true
}
],
"status": "passed"
},
{
"field": "given names",
"values": [{
"id": "drivingLicenseFront",
"value": "",
"isAvailable": true
},
{
"id": "passport",
"value": "",
"isAvailable": true
}
],
"status": "passed"
},
{
"field": "date of birth",
"values": [{
"id": "drivingLicenseFront",
"value": "25.07.1974",
"isAvailable": true
},
{
"id": "passport",
"value": "05 JUN /JOIN 57",
"isAvailable": true
}
],
"status": "passed"
}
];

for (let x = data.length - 1; x >= 0; x--) {
let count = 0; //Observe change in this line
var dataValueLength = data[x].values.length;
for (let y = 0; y < data[x].values.length; y++) {
if (data[x].values[y].value === "") {
count++;
}
}
if (dataValueLength == count) {
data.splice(x, 1)
}
}

console.log(JSON.stringify(data));

关于javascript - 如果javascript中所有值都为空,如何删除对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48189224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com