组合多个 json 并在 Angular UI 网格中显示

Combining multiple json and displaying it in Angular UI Grid

我正在尝试从多个来源获取 json 并希望在单个 Angular UI 网格中显示它。在所有这些来源中,第一个字段很常见。

数据格式:

来源:1

var one=[ 
      { col1: "Heading 1", col2: "First 12", col3: "First 13"},
      { col1: "Heading 2", col2: "First 22", col3: "First 23"},
      { col1: "Heading 3", col2: "First 32", col3: "First 33"},
      { col1: "Heading 4", col2: "First 42", col3: "First 43"},
      { col1: "Heading 5", col2: "First 52", col3: "First 53"}
    ]; 

来源:2

var two=[
      { col1: "Heading 1", col2: "Second 12", col3: "Second 13"},
      { col1: "Heading 2", col2: "Second 22", col3: "Second 23"},
      { col1: "Heading 3", col2: "Second 32", col3: "Second 33"},
      { col1: "Heading 4", col2: "Second 42", col3: "Second 43"},
      { col1: "Heading 5", col2: "Second 52", col3: "Second 53"}
    ];

我希望它像这样显示在网格中

来源:

var app = angular.module('plunker', ['ui.grid', 'ui.grid.selection']);

app.controller('MainCtrl', ['$scope', 'uiGridConstants', function($scope, uiGridConstants) {

var one=[ 
      { col1: "Heading 1", col2: "First 12", col3: "First 13"},
      { col1: "Heading 2", col2: "First 22", col3: "First 23"},
      { col1: "Heading 3", col2: "First 32", col3: "First 33"},
      { col1: "Heading 4", col2: "First 42", col3: "First 43"},
      { col1: "Heading 5", col2: "First 52", col3: "First 53"}
    ]; 1
     1
var two=[
      { col1: "Heading 1", col2: "Second 12", col3: "Second 13"},
      { col1: "Heading 2", col2: "Second 22", col3: "Second 23"},
      { col1: "Heading 3", col2: "Second 32", col3: "Second 33"},
      { col1: "Heading 4", col2: "Second 42", col3: "Second 43"},
      { col1: "Heading 5", col2: "Second 52", col3: "Second 53"}
    ];

  var finalObj = {

    "firstData":one,
    "secondData":two
  }


  console.log("finalObj"+JSON.stringify(finalObj));


  $scope.gridOptions = {
    columnDefs: [
        {field: 'firstData.col1', displayName: 'Column 1', width: 175},
      {field: 'firstData.col2', displayName: 'Column 2', width: '*'},
      {field: 'firstData.col3', displayName: 'Column 3', width: 120},
      {field: 'secondData.col2', displayName: 'Column 4', width: '*'},
      {field: 'secondData.col3', displayName: 'Column 5', width: 120}
    ],
    enableRowSelection: true,
    onRegisterApi: function(gridApi) {
      $scope.gridApi = gridApi;
    }
    };
  $scope.gridOptions=finalObj;

}]);

代码:查看攻击的 Plunkr http://plnkr.co/edit/ZUyJQInnygirvfohIhQo

1) $scope.gridOptions=finalObj;需要改为$scope.gridOptions.data=finalObj;

2) $scope.gridOptions.data 需要 array

试试这个:

function merge(obj1, obj2){
    return obj1.map(function(o1){
      return Object.assign({}, o1, {
        col4: obj2.find(function(o2){ return o1.col1 == o2.col1 }).col2,
        col5: obj2.find(function(o2){ return o1.col1 == o2.col1 }).col3
      })
    })
}

var finalObj = merge(one, two);

$scope.gridOptions.data=finalObj;

Plunker