2012-10-24 133 views
0

鉴于此JSON结构:淘汰赛JS映射嵌套观察到的阵列

{ 
    "categoryID" : 1, 
    "categoryName" : "Stupid Questions", 
    "questions" : [{ 
      "question" : [{ 
        "questionOptions" : [{ 
          "questionOptionID" : 1, 
          "optionText" : "It's top secret." 
         }, { 
          "questionOptionID" : 2, 
          "optionText" : "Because I am big and your small. I am right and your wrong." 
         }, { 
          "questionOptionID" : 3, 
          "optionText" : "I will gladly pay you Tuesday for a hamburger today." 
         }, 
        ], 
        "questionType" : "checkbox", 
        "questionText" : "Why can't we use more abstract table and column names?", 
        "summary" : "Question of the year" 
       } 
      ] 
     } 
    ] 
} 

我想映射两个问题,并questionOptions到模板和templateOptions:

{ 
    "categoryID" : 1, 
    "categoryName" : "Stupid Questions", 
    "templates" : [{ 
      "template" : [{ 
        "templateOptions" : [{ 
          "templateOptionID" : 1, 
          "optionText" : "It is top secret." 
         }, { 
          "QuestionOptionID" : 2, 
          "OptionText" : "Because we are lazy." 
         }, { 
          "QuestionOptionID" : 3, 
          "OptionText" : "I will gladly pay you Tuesday for a hamburger today." 
         }, 
        ], 
        "QuestionType" : "checkbox", 
        "QuestionText" : "Why can't we use more abstract table and column names?", 
        "Summary" : "Question of the year" 
       } 
      ] 
     } 
    ] 
} 

这里是开始我的淘汰赛映射对象:

var templateMapping = { 
    'templates': { 
     templates: function(data) { 
      return ko.utils.unwrapObservable(data.questions); 
     } 
    } 
    //how do I map observable array of question options to observable array of template options here? 
}; 

该映射的关键在于子对象具有一个不同的结构(不像这个问题 - https://stackoverflow.com/a/7535397/466321)。看起来,我发现的所有映射示例都没有涉及这可能如何完成,而且我也没有尝试过一些我自己的理论。

+0

映射器不工作的方式。我使用对象模型并使属性可观察。这并不意味着要这样做。 –

回答

1

@Jeff Mercado是对的。该映射器不是为此设计的。为了实现你的目标,它需要一些递归的JavaScript。

function myTransform(string) { 
    // case-insensitive replace 
    return string.replace(/question/i,'template'); 
} 

function transformObject(source) { 
    var result = {} 
    for(var key in source) { 
     if(!source.hasOwnProperty(key)) continue; 
     var value = source[key]; 
     var newKey = myTransform(key); 
     if(Object.prototype.toString.call(value) == "[object Array]") { 
      result[newKey] = []; 
      for(var i in value) { 
       if(!value.hasOwnProperty(i)) continue; 
       result[newKey][i] = transformObject(value[i]); 
      } 
     } 
     else if(Object.prototype.toString.call(value) == "[object Object]") { 
      result[newKey] = transformObject(value); 
     } 
     else { 
      result[newKey] = value; 
     } 
    } 
    return result; 
} 

var wow = transformObject(json); 

看到这个fiddle