jQuery JSON 获取子数据的长度

时间:2021-06-24 12:40:56

标签: jquery json

我有一些以以下格式返回的 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..."
                }
            ]
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

你可以像下面这样操作

// 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') 
相关问题