我有一个json,如果它存在或不为空,我希望获取一些值。在JSON下面,我想提取"questionGroup“的”选项“。挑战是在某些地方"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
      }
    }
  ]发布于 2019-11-12 04:49:25
只需检查这些选项是否未定义。
// 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;
    }
});发布于 2019-11-12 05:14:53
为此,您可以使用过滤器方法。
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);发布于 2019-11-12 04:42:28
surveyQuestions.filter(s => s.questionGroup && Object.keys(s.questionGroup).length)https://stackoverflow.com/questions/58812084
复制相似问题