繁体   English   中英

循环遍历嵌套数组

[英]looping through nested arrays

我有一个数组数组,实际上是一系列表行。

0: Array[5]
0: ""
1: ""
2: "Is there at least one teacher or other adult in this school that you can talk to if you have a problem?"
3: ""
4: ""

1: Array[5]
0: ""
1: ""
2: "Yes"
3: "No"
4: "Not sure"

2: Array[5]
0: "Grade"
1: "6th"
2: "55%"
3: "20%"
4: "25%"

如果我遇到某些内容,即“?” 我想将该行分配给新的JSON对象。 我正在使用forEach循环遍历数组,如下所示:

function parseRow(element, index, array) {
    element.forEach(parseCell);
  }
function parseCell(element, index, array) {
    if (element.indexOf("?") > -1) { // if it is a question
      //do something to tell indicate this is a question row

    }  else { 
      // table cell
    }
  }

我需要在我的目标中更加明确。 我有一个行值(作为数组),其中一些包含一个表定义问题,其中一些是标题行,其中一些是表行。 我想吐出一个格式化的JSON对象:

 {
"question": "Is there at least...",
"Category": "Overall",
"Division" : "All",
"Yes" : "65.00%",
"No": "11.70%",
"Not Sure" : "23.30%",
},
{
"question": "Is there at least...",
"Category" : "Grade",
"Division" : "6th",
"Yes" : "65.00%",
"No": "11.70%",
"Not Sure" : "23.30%",
},
{
"question": "Is there at least...",
"Category" : "Grade",
"Division" : "7th",
"Yes" : "65.00%",
"No": "11.70%",
"Not Sure" : "23.30%",
},

JSON对象可以更嵌套,这似乎是最容易处理的构建。

您可以使用可以返回对象的map函数,以便从元素数组中获取一系列问题:

function parseRow(element, index, array) {
   var questions = element.map(function(el,i){
       if(el.indexOf("?") > -1){
          return el;
       }
   });
}

这将为您提供一系列包含问题的元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM