gpt4 book ai didi

javascript - 检查 json 中的所有字段是否已设置且非空

转载 作者:行者123 更新时间:2023-12-05 02:42:44 25 4
gpt4 key购买 nike

我有一个这样的json

{
"serial": "34AS9831",
"sensor_type": "Foo",

"value_registered": {
"value_type": "temperature",
"value": 34.6,
"unit_of_measure": "celsius"
},

"value_registered_at": "24/08/2021 14:05:34"
}

我需要检查是否设置了所有字段,并且它们必须是非空的。

第一种解决方案如下:

try {
check_request(req, res);

let data = JSON.parse(req.body);

let isJSONBadFormatted =
data.serial == undefined ||
data.serial == null ||
data.sensor_type == undefined ||
data.sensor_type == null ||
data.value_registered == undefined ||
data.value_registered == null ||
data.value_registered.value_type == undefined ||
data.value_registered.value_type == null ||
data.value_registered.value == undefined ||
data.value_registered.value == null ||
data.value_registered.unit_of_measure == undefined ||
data.value_registered.unit_of_measure == null ||
data.value_registered_at == undefined ||
data.value_registered_at == null;

if(isJSONBadFormatted) {
unprocessable_json(res);
alert();
return;
}

insertDataIntoDB(data);

}catch(err){
/* TODO: implement alert function */
alert();
}

但是我不喜欢这样。有没有更优雅的方式来编写它的解决方案?

最佳答案

你可以试试这个功能:

const validate = (obj, validations) => 
validations.every(key => ![undefined, null].includes(key.split('.').reduce((acc, cur) => acc?.[cur], obj)));

只需要提供一个数组,其中包含每个不应为空的属性名称。

const validate = (obj, validations) => 
validations.every(key => ![undefined, null].includes(key.split('.').reduce((acc, cur) => acc?.[cur], obj)));

const data = {
"serial": "34AS9831",
"sensor_type": "Foo",

"value_registered": {
"value_type": "temperature",
"value": 34.6,
"unit_of_measure": "celsius"
},

"value_registered_at": "24/08/2021 14:05:34"
};

const validations = [
'serial',
'sensor_type',
'value_registered',
'value_registered.value_type',
'value_registered.value',
'value_registered.unit_of_measure',
'value_registered_at'
];


console.log(validate(data, validations));

关于javascript - 检查 json 中的所有字段是否已设置且非空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67296698/

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