我想将此 json 映射到自定义对象。问题是项目不是类型项目对象而是普通对象。我在这里缺少什么?
你可以在这里测试:http: //jsfiddle.net/5jhpE/
var json = [
{
id: 1,
items: [
{id: 1, name: 'item1'},
{id: 2, name: 'item2'},
{id: 3, name: 'item3'}
]
},
{
id: 2,
items: [
{id: 4, name: 'item4'},
{id: 5, name: 'item5'},
{id: 6, name: 'item6'}
]
},
]
function Data(data) {
ko.mapping.fromJS(data, {}, this);
}
function Item(data) {
ko.mapping.fromJS(data, {}, this);
}
var map = {
create: function(options) {
return new Data(options.data);
},
items: function(options) {
return new Item(options.data);
},
}
var res = ko.mapping.fromJS(json, map);
输出:
console.log(res());
[Data, Data]
--
console.log(res()[0].items());
[Object, Object, Object] <-- Here I want to have [Item, Item, Item]