3

我正在尝试将 JSON 传递给淘汰赛并显示它,并且我已经成功地为前几个元素这样做了。但是我遇到了嵌套对象的问题。我想要实现的是为每个 A1,A2,A3 / B1,B2,B3 显示 desc 和 value 字段。

我查看了一百万个示例并尝试了各种版本,但仍然无法弄清楚映射是如何工作的。

非常感谢您的帮助。

JS:

function jsonSubsetModel (desc,value){
    var self = this;
    self.desc = ko.observable(desc);
    self.value = ko.observable(value);
    }


    var myModel = function(){
        var jsonUrl = '/myjson.json';
        var self = this;
        var mapped = {};

        //Data
        self.date = ko.observable();
        self.time = ko.observable();

        self.set1 = ko.observableArray([]);
        self.set2 = ko.observableArray([]);



    $.getJSON(jsonUrl,function (data) {     
    self.date(data.Date);
    self.time(data.Time);   
    self.img(data.ImgURL);

    mapped = ko.mapping.fromJS(data);
    self.set1(mapped.SET1);
    self.set2(mapped.SET2);             
    });

    };  

    ko.applyBindings(new myModel());    

HTML:

<!-- This works -->
    <span data-bind="text: date"></span><br>
    <span data-bind="text: time"></span><br>
    <span data-bind="text: img"></span><br>

<!-- This doesn't -->    
    <p data-bind = "foreach:{data: set1, as:'subset'}">
    <span data-bind="text: subset.desc"></span>
    <span data-bind="text: subset.value"></span>    
    </p>

JSON:

{    
"Date":"21/02/2013",
"Time":"13:55",    
"SET1": {       
            "A1":{          
            "desc":"descA1",
            "value":"30",               
            },
            "A2":{          
            "desc":"descA2",
            "value":"30",
            },
            "A3":{          
            "desc":"descA3",
            "value":"30",
            }                                           
    },

    "SET2": {       
            "B1":{          
            "desc":"descA1",
            "value":"30",
            },
            "B2":{          
            "desc":"descA1",
            "value":"30",
            },
            "B3":{          
            "desc":"descA1",
            "value":"30",
            }                       
    }
}
4

1 回答 1

3

knockout.js foreachArray. _ 你提供的是一个对象。将您的对象更改为:

"SET1": [      
            {          
            "desc":"descA1",
            "value":"30",               
            },
            {          
            "desc":"descA2",
            "value":"30",
            },
            {          
            "desc":"descA3",
            "value":"30",
            }                                           
    ],
于 2013-02-12T11:58:08.103 回答