从下方JSON获取“ Root_Zones” 值的最佳方法是什么?
例如,如果我想要“全名”,那么我就这样做:
UserConnectResponse.Result_Data.Full_Name,
但是如果我想要Root_Zones
,Successor_Zones
,Water_Source_Groups
,那么我如何得到它们?因为我做的因为它给null!
这是功能逻辑:
const saveDbData = async (data) => {
console.log('THE JSON DATA IS:', JSON.stringify(data) + ' ' + 'ROWS');
const UserConnectResponse = data;
await insertUserConnectResponseData(
UserConnectResponse.Req_Type,
UserConnectResponse.Language_Code,
UserConnectResponse.User_ID,
UserConnectResponse.Session_ID,
UserConnectResponse.Session_Key,
UserConnectResponse.Client_Type,
UserConnectResponse.Result_Code,
UserConnectResponse.Result_Message,
UserConnectResponse.Result_Data.Full_Name,
UserConnectResponse.Result_Data.Root_Zones,
UserConnectResponse.Result_Data.Successor_Zones,
UserConnectResponse.Result_Data.Water_Source_Groups
)
.catch((err) => console.log('ERROR AFTER INSERT:', err))
.then((result) => console.log('RESULT AFTER INSERT:', data, result));
const fetchawesome = await fetchUserConnectResponseData();
console.log('tblUserConnectResponseData AFTER INSERT IS: :', fetchawesome);
};
这是JSON
{
"Req_Type": "string",
"Language_Code": "string",
"User_ID": "string",
"Session_ID": "string",
"Session_Key": "string",
"Client_Type": "string",
"Result_Code": 0,
"Result_Message": "string",
"Result_Data": {
"Full_Name": "string",
"Root_Zones": [
{
"Zone_ID": 0,
"Zone_Name": "string"
}
],
"Successor_Zones": [
{
"Zone_ID": 0,
"Zone_Name": "string"
}
],
"Water_Source_Groups": [
{
"Group_ID": 0,
"Group_Name": "string",
"Zone_ID": 0
}
]
},
"AccessDenied": "string"
}
答案 0 :(得分:0)
使用destructuring
作为默认值,或者使用optional chaining operator
。
const data = {
Req_Type: "string",
Language_Code: "string",
User_ID: "string",
Session_ID: "string",
Session_Key: "string",
Client_Type: "string",
Result_Code: 0,
Result_Message: "string",
Result_Data: {
Full_Name: "string",
Root_Zones: [
{
Zone_ID: 0,
Zone_Name: "string",
},
],
Successor_Zones: [
{
Zone_ID: 0,
Zone_Name: "string",
},
],
Water_Source_Groups: [
{
Group_ID: 0,
Group_Name: "string",
Zone_ID: 0,
},
],
},
AccessDenied: "string",
};
// Using destructuring
const {
Result_Data: {
Root_Zones = [],
Successor_Zones = [],
Water_Source_Groups = [],
} = {},
} = data;
// Using optional chaining operator (?.) and null coalescing operator (??)
const Root_ZonesAlt = data?.Result_Data?.Root_Zones ?? [];
console.log('Method1', Root_Zones);
console.log('Method2', Root_ZonesAlt);