遍历一个数组并验证一个数组中的总百分比不超过100%

时间:2018-07-28 23:00:57

标签: javascript node.js

    let data  = {
    "1st Company Shareholders": [
        {
            "controllingInterest": true,
            "fullLegalName": 'Comapny 2',
            "ownShareholders": true,
            "percentageOwnership": 50,
            "shareholders": [
              {
               "controllingInterest": true,
               "firstName": "Joe",
               "lastName": "ch",
               "middleName": "ch",
               "percentageOwnership": 60
              },
              {
             "controllingInterest": true,
            "fullLegalName": 'Comapny 3',
            "ownShareholders": true,
            "percentageOwnership": 30,
            "shareholders": [ ... goes on]
              }
              ]
        },
        {
            "controllingInterest": true,
            "fullLegalName": "Person 1",
            "ownShareholders": false,
            "shareholders": [],
            "percentageOwnership":30
        }
    ]
};

在上述情况下,第一家公司的总percentageOwnership为50 + 30(50是comapny2,来自Person1的是30)-需要验证其不超过100% 第二家公司的所有权总计为60 + 30-需要验证该所有权不超过100,依此类推

与上述公司3相似,它可以有很多股东-如果股东是公司,则可以在股东中拥有股东
在我的应用程序中,用户可以在嵌套结构中输入尽可能多的股东
我需要验证每个公司的股份百分比不会超过100%
有没有办法实现这一目标。在此先感谢

1 个答案:

答案 0 :(得分:0)

您可以尝试类似的操作,在迭代过程中跟踪列表中的无效股东。

var ShareHoldersArray = [
{
    "controllingInterest": true,
    "fullLegalName": 'ABC Corp',
    "ownShareholders": true,
    "percentageOwnership": 50,
    "shareholders": [
      {
       "controllingInterest": true,
       "firstName": "ch",
       "lastName": "ch",
       "middleName": "ch",
       "percentageOwnership": 50
      }
      ]
},
{
    "controllingInterest": true,
    "fullLegalName": "Punith",
    "ownShareholders": false,
    "shareholders": [],
    "percentageOwnership":30
}
]

function checkPercentageOwnership(companyShareHolder, invalidShareHolders){
  if (companyShareHolder["percentageOwnership"] > 100){
    invalidShareHolders.push(companyShareHolder["fullLegalName"])
  }

  if (companyShareHolder["ownShareholders"] === true){
    invalidShareHolders = checkIndividualShareHolders(companyShareHolder["shareholders"], invalidShareHolders)
  }

  return invalidShareHolders
}

function checkIndividualShareHolders(individualShareHolders, invalidShareHolders){
  for (var i = 0; i < individualShareHolders.length; i++){
    if (individualShareHolders[i]["percentageOwnership"] > 100){
      invalidShareHolders.push(individualShareHolders[i]["firstName"] + " " + individualShareHolders[i]["lastName"])
    }
  }

  return invalidShareHolders
}

invalidShareHolders = []
for (var i=0; i<shareHoldersArray.length; ++i){
  invalidShareHolders = checkPercentageOwnership(shareHoldersArray[i], invalidShareHolders)  
}

console.log(invalidShareHolders)