代码之家  ›  专栏  ›  技术社区  ›  Rolando

检查列表中键最多的对象的最佳方法是什么?

  •  0
  • Rolando  · 技术社区  · 5 年前

    我有一个列表,其中的对象具有不同数量的键。我希望确保从包含最多键的对象列表或对象本身的引用中获取索引。最好的方法是什么?

    我目前的做法是:

    let index = -1;
    let numKeys = 0;
    for(var i = 0; i < mylistofobjects.length; i++) { 
      if(Object.keys(mylistofobjects[i]).length > numKeys) {
        index = i;
      }
    }
    
    // by the end, index has the most keys
    

    在当今这个时代,有没有一种更智能/更短的方法来实现这一点,从而需要更少的代码?如果获取对象引用的方式比获取索引号的方式短。。我更喜欢对象引用。

    1 回复  |  直到 5 年前
        1
  •  1
  •   CertainPerformance    5 年前

    一个选择是 reduce ,在累加器中保留迄今为止找到的键最多的对象:

    const objWithMostKeys = mylistofobjects.reduce((bestSoFar, thisObj) => (
      Object.keys(bestSoFar).length >= Object.keys(thisObj).length ? bestSoFar : thisObj
    ));
    

    它并不完全有效,因为它会在每次迭代中检查累加器的密钥数,而不是缓存它,但是缓存它需要更多的代码:

    let maxKeyCount = Object.keys(mylistofobjects[0]).length;
    const objWithMostKeys = mylistofobjects.reduce((bestSoFar, currObj) => {
      const currKeyCount = Object.keys(currObj).length;
      if (currKeyCount > maxKeyCount) {
        maxKeyCount = currKeyCount;
        return currObj;
      }
      return bestSoFar;
    });
    

    这假设 mylistofobjects 它不是空的。如果可能的话,可以加一个 .length 提前检查,提前返回/抛出错误(或你需要做的任何事情),而不是继续。