遍历嵌套数组

4

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

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对象可能会更加嵌套,但这似乎是最容易处理的构建方式。


如果你想保留 forEach 循环,你需要一个共同的闭包。或者,使用 map,然后你可以返回一些处理过的东西,以便 parseRow 可以使用。 - Bartek Banachewicz
我支持@BartekBanachewicz的观点。当遇到?字符时,你具体想要做什么? - jonny
当遇到"?"时,我想将该元素分配给一个新的对象{"question": element},但我也想将其作为新表的标记。@JonathanBrooks - icicleking
1个回答

2
你可以使用 map 函数来返回对象,以从元素数组中获取问题数组:
function parseRow(element, index, array) {
   var questions = element.map(function(el,i){
       if(el.indexOf("?") > -1){
          return el;
       }
   });
}

这将为您提供一个包含问题的元素数组。

谢谢,我接受答案,因为它回答了基本问题,谢谢。 - icicleking

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接