【问题标题】:jQuery JSON getting length of sub datajQuery JSON获取子数据的长度
【发布时间】:2021-06-24 12:40:56
【问题描述】:

我有一些以以下格式返回的 JSON 数据。我正在寻找是否有一种简单的方法来获取问题总数(有 9 个)而无需通过 3 个子支柱进行任何循环?还是我不得不循环遍历每个部分并以这种方式计算问题?

{
    "name": "Leadership & Strategy",
    "description": "Ineffective management costs...",
    "subpillars": [
        {
            "name": "Leadership Behaviours",
            "sub_text": "How you lead and inspire..",
            "slug": "leadership-behaviours",
            "questions": [
                {
                    "id": 1,
                    "text": "What methods..."
                },
                {
                    "id": 2,
                    "text": "How do you..."
                },
                {
                    "id": 3,
                    "text": "How many times..."
                },
                {
                    "id": 4,
                    "text": "Which of the following..."
                }
            ]
        },
        {
            "name": "Vision & Values",
            "sub_text": "A meaningful vision...",
            "slug": "vision-values",
            "questions": [
                {
                    "id": 6,
                    "text": "Which of the following..."
                },
                {
                    "id": 7,
                    "text": "In the last year..."
                },
                {
                    "id": 23,
                    "text": "In 10 years time..."
                }
            ]
        },
        {
            "name": "External Collaboration",
            "sub_text": "Learning from peers...",
            "slug": "external-collaboration",
            "questions": [
                {
                    "id": 21,
                    "text": "Which of these statements..."
                },
                {
                    "id": 29,
                    "text": "The last time you developed improvements..."
                }
            ]
        }
    ]
}

【问题讨论】:

    标签: jquery json


    【解决方案1】:

    你可以这样做

    // obj is your JSON
    const obj = { ...your JSON... }
    
    let count = 0
    obj.subpillars.forEach(item => {
        count += item.questions.length
    }
    
    console.log(count + ' questions are available') 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-13
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 2014-04-30
      • 1970-01-01
      相关资源
      最近更新 更多