JSON对象格式/合并

时间:2017-03-30 13:12:23

标签: javascript angularjs

我有以下两个变量:

var parent: [{
  "SNO": "869",
  "Name": "ABC"
}, {
  "SNO": "800",
  "Name": "CCC"
}]
var Cost = [{
  "NO": "869",
  "Amnt": 100
}, {
  "NO": "800",
  "Amnt": 200
}, {
  "NO": "800",
  "Amnt": 560
}]

and the end updated result I want something like.
{
  "parent": [{
      "SNO": "869",
      "Name": "ABC",
      "Cost": [{
          "NO": "869",
          "Amnt": 100
        },
        {
          "NO": "869",
          "Amnt": 200
        },
        {
          "NO": "869",
          "Amnt": 560
        }
      ]
    },
    {
      "SNO": "800",
      "Name": "XYZ",
      "Cost": [{
          "NO": "800",
          "Amnt": 100
        },
        {
          "NO": "800",
          "Amnt": 200
        },
        {
          "NO": "800",
          "Amnt": 560
        }
      ]
    }
  ]
}

有人可以建议我如何使它成为可能。

2 个答案:

答案 0 :(得分:0)

您可以使用哈希表来引用相同的父项。

var parent = [{ SNO: "869", Name: "ABC" }, { SNO: "800", Name: "CCC" }],
    cost = [{ NO: "869", Amnt: 100 }, { NO: "800", Amnt: 200 }, { NO: "800", Amnt: 560 }],
    hash = Object.create(null),
    result = { Parent: parent.map(function (a) { return hash[a.SNO] = a; }) };

cost.forEach(function (a) {
    (hash[a.NO].Cost = hash[a.NO].Cost || []).push(a);
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

希望这就是你要找的东西。

angular.module("app", []).controller("myCtrl", function($scope) {
  $scope.parent = [{
    "SNO": "869",
    "Name": "ABC"
  }, {
    "SNO": "800",
    "Name": "CCC"
  }];

  $scope.Cost = [{
    "NO": "869",
    "Amnt": 100
  }, {
    "NO": "800",
    "Amnt": 200
  }, {
    "NO": "800",
    "Amnt": 560
  }];

  $scope.mergeArr = function(arr1, arr2) {
    var arrTmp = [];
    if (Array.isArray(arr1)) {
      arrTmp.push(...arr1);
    } else {
      arrTmp.push(arr1);
    }

    arrTmp.forEach(function(item) {
      var costArr = arr2.filter(function(item2) {
        return item2.NO === item.SNO;
      });

      if (costArr.length > 0) {
        if (!item.COST) {
          item["COST"] = [];
        }

        costArr.forEach(function(cost) {
          item.COST.push(cost);
        })
      }
    });
    console.log(arrTmp);
    return {
      "Parent": arrTmp
    };
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  <div>
    <ui>
      <li ng-repeat="project in mergeArr(parent, Cost).Parent">
        {{project.SNO}} - {{project.Name}}
      </li>
    </ui>
  </div>
</div>