jQuery JSON获取子数据的长度



我有一些JSON数据,这些数据以下面的格式返回。我想看看是否有一种简单的方法可以在不必对3个子像素进行任何循环的情况下获得问题总数(共有9个(?还是我不得不循环浏览每一节并以这种方式计算问题?

{
"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..."
}
]
}
]
}

您可以像以下一样执行

// 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') 

最新更新