按数据类型自定义KnockOut Mapping

时间:2018-03-14 19:54:59

标签: javascript knockout.js knockout-mapping-plugin

我有一个看起来像这样的数据列表:

 "containers": [{
      "Id": 1,
      "Description": "B",
      "Properties": {}
},
 {
      "Id": 2,
      "Description": "A",
      "Properties": {}
},
 {
      "Id": 3,
      "Description": "B",
      "Properties": {}
},
 {
      "Id": 4,
      "Description": "A",
      "Properties": {}
}, 
 {
      "Id": 5,
      "Description": "C",
      "Properties": {}
}]

使用knockout和knockout mapping plugging,我的目标是创建一个自定义映射来创建类似的东西:

 "containers": [{
    "A":[{
          "Id": 2,
          "Description": "A",
          "Properties": {}
        },
        {
          "Id": 4,
          "Description": "A",
          "Properties": {}
        }],
    "B":[{
          "Id": 1,
          "Description": "B",
          "Properties": {}
        },
        {
      "Id": 3,
      "Description": "B",
      "Properties": {}
        }], 
    "C"{
      "Id": 1,
      "Description": "C",
      "Properties": {}
    }]]

根据对象的描述将对象分组到数组中。

我试过这样的事情:

var mapping = {
    create: function (options) {
        var arrdata = [];
        if (!(options.data.Description in arrdata)) {
            arrdata[options.data.Description] = [];
        }
        arrdata[options.data.Description].push(ko.mapping.fromJS(options.data));
        return arrdata;

    }
}

但它只是在它自己的数组中的每个对象,所以而不是我期待的三个数组我的5个数组,每个数组大小为1。如何告诉Knockout Mapping合并数组或创建一个完成此操作的映射?

1 个答案:

答案 0 :(得分:0)

var containers = [{
      "Id": 1,
      "Description": "B",
      "Properties": {}
},
 {
      "Id": 2,
      "Description": "A",
      "Properties": {}
},
 {
      "Id": 3,
      "Description": "B",
      "Properties": {}
},
 {
      "Id": 4,
      "Description": "A",
      "Properties": {}
}, 
 {
      "Id": 5,
      "Description": "C",
      "Properties": {}
}]

//Remap array of objects to object with arrays of objects
groupedByDescription = {};

containers.forEach(function(c){
  //Create object properties based on container description, and create array / push to array
  if(groupedByDescription.hasOwnProperty(c.Description)){
    groupedByDescription[c.Description].push(c);
  }else{
    groupedByDescription[c.Description] = [c];
  }
});

console.log(groupedByDescription);

JS小提琴: https://jsfiddle.net/b7g7s5h9/9/

这对你有帮助吗?应该是你要求的,但不是使用ko映射。