将json对象链接到多个对象

时间:2018-09-18 11:05:19

标签: javascript angularjs json hyperlink nested

我正在尝试将json对象链接到多个对象。

    $scope.persons = [
        {"prename":"Max", "surname":"Shepherd"},
        {"prename":"Sarah", "surname":"Shepherd"}
    ];
    $scope.contracts = [
        {"contract":"liability", "payment":"8.40"},
        {"contract":"health", "payment":"48.12"}
    ];

// Save new Person
    $scope.newPerson = {};
    $scope.savePerson = function() {
        $scope.persons.push($scope.newPerson);
        $scope.newPerson = {};
    }
// Save new Contract
    $scope.newContract = {};
    $scope.saveContract = function() {
        $scope.contract.push($scope.newContract);
        $scope.newContract = {};
    }

如何保存新合同并将其链接/嵌套到2个人。 例如责任合同应嵌套两个人。 健康合同应仅嵌套给1个人。 但是合同也应该是自己的对象。

最终数组应该看起来像这样:

$scope.persons = [
  {
  "prename":"Max", 
  "surname":"Shepherd",
      "contracts": {
      {"contract":"liability", "payment":"8.40"}
    }
  },
  {
  "prename":"Sarah",
  "surname":"Shepherd",
    "contracts": {
      "contract":"liability", "payment":"8.40"
      "contract":"health", "payment":"48.12"
    }
  }
];

$scope.contracts = [
    {"contract":"liability", "payment":"8.40"},
    {"contract":"health", "payment":"48.12"}
];

1 个答案:

答案 0 :(得分:0)

您可以添加合同ID,然后将ID链接到拥有合同的每个人。

{“合同”:“责任”,“付款”:“ 8.40”,“合同密钥”:“ 123”}, {“合同”:“健康”,“付款”:“ 48.12”,“合同密钥”:“ 321”}

$ scope.persons = [   {   “ prename”:“ Max”,   “姓”:“牧羊人”,       “合同”:{       “ 123”,       “ 321”     }   },   {   “ prename”:“ Sarah”,   “姓”:“牧羊人”,     “合同”:{       “ 123”     }   } ];

然后,您将需要一个函数来搜索正确的合约

function findContractForAllPeople(){
   angular.forEach($persons,function(key,values){
        angular.forEach(values,function(DataKey,val){
          angular.forEach($contracts,function(contractKey,contractDetails) 

           if(DataKey === "contracts"){
             if($scope.contracts.contractKey === val){
               $scope.finalArray[prename] = {"contracts":contractDetails }
           }
        })
      })
   })
}

这将创建一个看起来像这样的对象

{
Max:{
"contracts":{"contract":"liability", "payment":"8.40","contractKey":"123"},
{"contract":"health", "payment":"48.12","contractKey":"321"}}
},
Sarah:{
{"contract":"liability", "payment":"8.40","contractKey":"123"}
}