2015-11-16 121 views
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对象可以是多个嵌套,这只是似乎是最容易处理的构建。

+0

如果你想保留'forEach'循环,你需要一个通用闭包。或者,使用'map',然后确实可以将处理后的内容返回到'parseRow'可以使用的表单中。 –

+0

我与@BartekBanachewicz。在遇到“?”字符时,你想要做什么? –

+0

当遇到“?”我想将元素赋值给newObj {“question”:element},但我也想将它作为新表的标记。 @JonathanBrooks – icicleking

回答

2

您可以使用地图功能,可以为了返回对象从您的元素数组得到问题的数组:

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

而且这会给你包含一个问题元素的数组。

+0

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