英文:
how to simplify undefined check?
问题
{
"I'd like to simplify JSON object check for undefined values:": "我想简化对未定义值的 JSON 对象检查:",
"{\n body: {\n data: {\n names: [\n {\n firstName: 'John'\n },\n {\n firstName: 'Johnn'\n }\n ]\n }\n }\n}": " {\n body: {\n data: {\n names: [\n {\n firstName: 'John'\n },\n {\n firstName: 'Johnn'\n }\n ]\n }\n }\n}",
"So if I do it like this then it throws an exception if names is an empty array []:": "因此,如果我像这样做,如果 names 是一个空数组 [],它会引发异常:",
"body?.data?.names[0]?.firstName": "body?.data?.names[0]?.firstName",
"So should I go old way like this?": "那我应该像这样回到旧的方式吗?",
"if (\n body &&\n body.data &&\n body.data.names &&\n body.data.names.length > 0 &&\n body.data.names[0] &&\n body.data.names[0].firstName\n ) {": "if (\n body &&\n body.data &&\n body.data.names &&\n body.data.names.length > 0 &&\n body.data.names[0] &&\n body.data.names[0].firstName\n ) {",
"// ....\n}": "// ....\n}"
}
英文:
I'd like to simplify JSON object check for undefined values:
{
body: {
data: {
names: [
{
firstName: 'John'
},
{
firstName: 'Johnn'
}
]
}
}
}
So if I do it like this then it throws an exception if names is an empty array []:
body?.data?.names[0]?.firstName
So should I go old way like this?
if (
body &&
body.data &&
body.data.names &&
body.data.names.length > 0 &&
body.data.names[0] &&
body.data.names[0].firstName
) {
// ....
}
答案1
得分: 2
您可以尝试使用以下方式进行undefined
检查,使用optional chaining (?.)
和 nullish coalescing (??)
运算符:
const data = {
body: {
data: {
names: [
{
firstName: 'John'
},
{
firstName: 'Johnn'
}
]
}
}
};
// 测试
const firstName = data?.body?.data?.names?.[0]?.firstName ?? 'Unknown';
console.log(firstName); // 'John';
// 测试:未定义
const dataWithoutNames = {
body: {
data: {}
}
};
const unknownName = dataWithoutNames?.body?.data?.names?.[0]?.firstName ?? 'Unknown';
console.log(unknownName); // 'Unknown';
英文:
You can try undefined
check using optional chaining (?.)
and nullish coalescing (??)
operators like the following way:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const data = {
body: {
data: {
names: [
{
firstName: 'John'
},
{
firstName: 'Johnn'
}
]
}
}
};
//test
const firstName = data?.body?.data?.names?.[0]?.firstName ?? 'Unknown';
console.log(firstName);//'John'
//test: undefined
const dataWithoutNames = {
body: {
data: {}
}
};
const unknownName = dataWithoutNames?.body?.data?.names?.[0]?.firstName ?? 'Unknown';
console.log(unknownName);//'Unknown'
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论