我有一个json,想获取一些值(如果存在或不为null)。 从JSON下面,我想提取“ questionGroup”的“ options”。挑战在某些地方“ questionGroup”是空的。
"surveyQuestions": [
{
"questionTitle": "Enter your name",
"questionType": "Text",
"questionGroup": {}
},
{
"questionTitle": "Enter your age",
"questionType": "Number",
"questionGroup": {}
},
{
"questionTitle": "Select your gender",
"questionType": "Single choice",
"questionGroup": {
"options": [
{
"optionText": "Male"
},
{
"optionText": "Female"
}
],
"showRemarksBox": false
}
}
]
答案 0 :(得分:1)
只需检查选项是否未定义。
// Iterate over survey questions
this.surveyQuestions.forEach( question => {
// Check if present or not
if(question.questionGroup.options!=undefined){
console.log(question.questionGroup.options);
return question.questionGroup.options;
}
});
答案 1 :(得分:1)
您可以为此使用filter方法。
let data = {"surveyQuestions": [
{
"questionTitle": "Enter your name",
"questionType": "Text",
"questionGroup": {}
},
{
"questionTitle": "Enter your age",
"questionType": "Number",
"questionGroup": {}
},
{
"questionTitle": "Select your gender",
"questionType": "Single choice",
"questionGroup": {
"options": [
{
"optionText": "Male"
},
{
"optionText": "Female"
}
],
"showRemarksBox": false
}
}
]}
let result = Array.from(data.surveyQuestions.filter(o => o.questionGroup.options), ({questionGroup}) => questionGroup.options);
console.log(result);
答案 2 :(得分:0)
surveyQuestions.filter(s => s.questionGroup && Object.keys(s.questionGroup).length)