Javascript:根据深度未知的属性对对象数组进行排序

时间:2019-05-30 07:27:53

标签: javascript

默认情况下,我必须在页面上的对象数组(例如端口)中显示最常用的属性值。某些属性位于端口对象的第一级,而某些属性则进一步是端口对象的“功能”键的属性。

端口:

"jeremykenedy/laravel-blocker": "^1.0",

我编写了一个函数,该函数为我提供了最频繁的属性,但是仅当该属性位于根级别时才起作用。例如。 'uplink','mode'等。但是,如果我传递了'poecapable',而后者又是port.config键的属性,则我的功能将失败。

{
    "accessVlan": 1,
    "accessVlanName": 1,
    "capabilities": {
      "maxPoePower": 30000,
      "supportedSpeeds": null,
      "poeCapable": true
    },
    "cloudUplink": false,
    "connectivity": "N/A",
    "description": "My Favorite por",
    "dhcpSnoopingTrusted": false,
    "enabled": true,
    "isolation": null,
    "isTenGig": false,
    "linkSpeed": null,
    "mode": "ACCESS",
    "name": "1/0/3",
    "poe": false,
    "poeFast": false,
    "poeMaxPower": 13000,
    "poePriority": "LOW",
    "poePerpetual": true,
    "poeDisablePortOnOverdrawn": false,
    "staticIpAddress": null,
    "staticIpNetmask": null,
    "totUsage": "N/A",
    "trunkAllowedVlans": [],
    "trunkAllowedVlansNames": "",
    "trunkNativeVlan": null,
    "trunkNativeVlanName": null,
    "udld": null,
    "uplink": false,
    "label": "3"
  }

如果我打电话,此功能将正常工作

const findMostFreq = (arr, propertyname) => {
  // console.log(propertyname);
  let proValArr = [...arr];
  proValArr.sort(function(a, b) {
    let v1 = a[propertyname];
    console.log('v1 is ', v1);
    let v2 = b[propertyname];
    if (v1 < v2) {
      return -1;
    }
    if (v1 > v2) {
      return 1;
    }
    if (v1 === v2) {
      return 0;
    }
  });

  //  console.log(proValArr);
  let propValMax = proValArr[0][propertyname];
  let propValLast = propValMax;
  let count = 0;
  let maxcount = 0;
  for (let i in proValArr) {
    if (propValLast === proValArr[i][propertyname]) {
      count += 1;
    } else {
      count = 1;
    }
    if (count > maxcount) {
      maxcount = count;
      propValMax = propValLast;
    }
    propValLast = proValArr[i][propertyname];
  }

  return propValMax;
};

但不是

findMostFreq(props.ports, 'uplink')

0 个答案:

没有答案