[英]What is the best way to check for the object with the most keys in a list?
I have a list that has objects with a varying amount of keys.我有一个列表,其中包含具有不同数量键的对象。 I want to make sure that I get the index from the list of the object with the most keys OR the reference to the object itself.
我想确保我从具有最多键的对象列表中获取索引或对对象本身的引用。 What is the best way to do this?
做这个的最好方式是什么?
My current approach is:我目前的做法是:
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
Is there a smarter/shorter way to do this that would require less code in this day and age?有没有更聪明/更短的方法来做到这一点,在这个时代需要更少的代码? If the way to get the object reference is shorter than the way to get the index number.. I would prefer the object reference.
如果获取对象引用的方式比获取索引号的方式短..我更喜欢对象引用。
One option is to reduce
, keeping in the accumulator the object with the most keys found so far:一种选择是
reduce
,将迄今为止找到的具有最多键的对象保留在累加器中:
const objWithMostKeys = mylistofobjects.reduce((bestSoFar, thisObj) => (
Object.keys(bestSoFar).length >= Object.keys(thisObj).length ? bestSoFar : thisObj
));
It's not entirely efficient because it checks the accumulator's number of keys on every iteration, rather than caching it, but caching it will require a bit more code:它并不完全有效,因为它在每次迭代时检查累加器的键数,而不是缓存它,但是缓存它需要更多的代码:
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;
});
This assumes that the mylistofobjects
isn't empty.这假设
mylistofobjects
不为空。 If that's a possibility, probably add a .length
check beforehand, and return early / throw an error (or whatever you need to do) instead of proceeding.如果这是可能的,可能会事先添加一个
.length
检查,并提前返回/抛出错误(或您需要做的任何事情)而不是继续。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.