合并具有多个属性的多个if语句

时间:2019-06-04 13:29:42

标签: javascript jquery html

我正在研究使用循环将这段代码合并并缩小为一个switch语句或其他方法,我将如何实现呢?到目前为止,这是对我有用的东西,但我还有其他items[i].ApplicationType,例如'OneDrive','Teams'等。

for(i = 0; i < items.length; i++)
{
    if(items[i].ComputerType == 'Windows' && items[i].RequestType == 'Single User' && items[i].ApplicationType == 'OneDrive')
    {
        ODwindows += 1;
    }
    else if(items[i].ComputerType == 'Windows' && items[i].RequestType == 'Single User' && items[i].ApplicationType == 'Teams')
    {
        Teamswindows += 1;
    }
    else if(items[i].ComputerType == 'Mac' && items[i].RequestType == 'Single User' && items[i].ApplicationType == 'OneDrive')
    {
        ODmac += 1;
    }
    else if(items[i].ComputerType == 'Mac' && items[i].RequestType == 'Single User' && items[i].ApplicationType == 'Teams')
    {
        Teamsmac += 1;
    }
    else if(items[i].ComputerType == 'Both' && items[i].RequestType == 'Team' && items[i].ApplicationType == 'OneDrive')
    {
        ODboth += 1;
    }
    else if(items[i].ComputerType == 'Both' && items[i].RequestType == 'Team' && items[i].ApplicationType == 'Teams')
    {
        Teamsboth += 1;
    }
}

3 个答案:

答案 0 :(得分:6)

您可以采用不同类型的对象并通过嵌套属性来计数。

function setCookie($input) {
  setcookie('uname', $input, time() + 60 * 30);
  return $input;
}

if(!isset($_COOKIE['uname'])) {
    $uname  = setCookie($whatever);
} else {
    $uname = $_COOKIE['uname'];
}

echo "Cookie value: " . $uname;

答案 1 :(得分:0)

您可以为ComputerTypeRequestTypeApplicationType(用_隔开)的每个唯一组合创建密钥。然后使用destructuring将每个计数都赋给变量:

const output = {};

items.forEach(o => {
    const key = [o.ComputerType, o.RequestType, o.ApplicationType].join('_')
    output[key] = output[key] + 1 || 1
})

const {
    ['Windows_Single User_OneDrive']: ODwindows, 
    ['Windows_Single User_Teams']: Teamswindows, 
    ['Mac_Single User_OneDrive']: ODmac, 
    ['Mac_Single User_Teams']: Teamsmac, 
    ['Both_Team_Teams']: ODboth, 
    ['Both_Team_Teams']: Teamsboth
} = output;

答案 2 :(得分:0)

    const items = [{ComputerType: "Windows", RequestType:"Single", ApplicationType: "OneDrive"}]
    const countObj = items.reduce((accum, item) => {
      const { ComputerType, RequestType, ApplicationType } = item
      const key = `${ComputerType}_${RequestType}_${ApplicationType}`
      return { 
        ...accum,
        [key]: accum[key] ? accum[key] + 1 : 1
      }
    }, {})
    console.log(countObj)