因此,我试图检查某些JSON数据是否包含某个键,如果包含,则显示该键值,但我一直得到一个错误“TypeError:无法读取未定义的属性'CurrentTextValue'
如何检查某个键是否存在,以及它是否显示了它的值。
null
var carj = '[{ "Description": "SAAB 900 S CONVERTIBLE", "RegistrationYear": "1993", "CarMake": { "CurrentTextValue": "SAAB" }, "CarModel": { "CurrentTextValue": "900 S CONVERTIBLE" }, "MakeDescription": { "CurrentTextValue": "SAAB" }, "ModelDescription": { "CurrentTextValue": "900 S CONVERTIBLE" }, "EngineSize": { "CurrentTextValue": "1985" }, "BodyStyle": { "CurrentTextValue": "Motorbike" }, "FuelType": { "CurrentTextValue": "PETROL" }, "Variant": "", "Colour": "BLACK", "VehicleIdentificationNumber": "YS3AD75S1P7004905", "KType": "", "EngineNumber": "B202S3M03P032338" }]';
carj2 = $.parseJSON(carj);
if(carj2[0].NumberOfDoors.CurrentTextValue != '') {
console.log(carj2[0].NumberOfDoors.CurrentTextValue);
} else {
console.log('i dont have doors');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
null
null
var carj = '[{ "Description": "SAAB 900 S CONVERTIBLE", "RegistrationYear": "1993", "CarMake": { "CurrentTextValue": "SAAB" }, "CarModel": { "CurrentTextValue": "900 S CONVERTIBLE" }, "MakeDescription": { "CurrentTextValue": "SAAB" }, "ModelDescription": { "CurrentTextValue": "900 S CONVERTIBLE" }, "EngineSize": { "CurrentTextValue": "1985" }, "BodyStyle": { "CurrentTextValue": "Motorbike" }, "FuelType": { "CurrentTextValue": "PETROL" }, "Variant": "", "Colour": "BLACK", "VehicleIdentificationNumber": "YS3AD75S1P7004905", "KType": "", "EngineNumber": "B202S3M03P032338" }]';
carj2 = $.parseJSON(carj);
// Method 1
if ("numberOfDoors" in carj2[0]) {
console.log(carj2[0].NumberOfDoors.CurrentTextValue);
} else {
console.log('i dont have doors');
}
// Method 2
console.log(carj2[0].NumberOfDoors?.CurrentTextValue || "i dont have doors");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
您需要首先找到NumberOfDoors,然后查找值
这里我使用一个三值运算符输出
null
const carj = '[{ "Description": "SAAB 900 S CONVERTIBLE", "RegistrationYear": "1993", "CarMake": { "CurrentTextValue": "SAAB" }, "CarModel": { "CurrentTextValue": "900 S CONVERTIBLE" }, "MakeDescription": { "CurrentTextValue": "SAAB" }, "ModelDescription": { "CurrentTextValue": "900 S CONVERTIBLE" }, "EngineSize": { "CurrentTextValue": "1985" }, "BodyStyle": { "CurrentTextValue": "Motorbike" }, "FuelType": { "CurrentTextValue": "PETROL" }, "Variant": "", "Colour": "BLACK", "VehicleIdentificationNumber": "YS3AD75S1P7004905", "KType": "", "EngineNumber": "B202S3M03P032338" }]';
const carj2 = $.parseJSON(carj);
const NumberOfDoors = carj2[0].NumberOfDoors;
console.log( NumberOfDoors ? NumberOfDoors.CurrentTextValue : 'I don\'t have doors');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>