我正在尝试传递一个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",
            }
    }
}

最佳答案

knockout.js foreachArray一起使用。您提供的是一个对象。将对象更改为:

"SET1": [
            {
            "desc":"descA1",
            "value":"30",
            },
            {
            "desc":"descA2",
            "value":"30",
            },
            {
            "desc":"descA3",
            "value":"30",
            }
    ],

09-07 00:22