JavaScript-用唯一属性标识对象



我已经设法确定了计数属性中的最高数字,但我想记录与该数字相关的对象,即记录具有最高计数的对象。我该怎么做?

var objects = {
    object1: {username: 'mark', count: 3},
    object2: {username: 'dave', count: 5},
    object3: {username: 'lucy', count: 2},
};
var maxBap = Math.max.apply(Math,objects.map(function(o){return o.count;}));
console.log(maxBap);

感谢

使用.reduce()而不是.map()来获得所需的目标。

在这里,我返回result对象的键。如果您愿意,可以直接返回对象。

var objects = {
    object1: {username: 'mark', count: 3},
    object2: {username: 'dave', count: 5},
    object3: {username: 'lucy', count: 2},
};
var res = Object.keys(objects).reduce(function(resKey, key) {
  return objects[resKey].count > objects[key].count ? resKey : key
})
document.querySelector("pre").textContent = res + ": " +
  JSON.stringify(objects[res], null, 4);
<pre></pre>


如果objects是一个数组,那么您仍然可以使用.reduce(),只是没有Object.keys()。这将直接返回对象,这在第一个解决方案中有所提及。

var objects = [
    {username: 'mark', count: 3},
    {username: 'dave', count: 5},
    {username: 'lucy', count: 2},
];
var res = objects.reduce(function(resObj, obj) {
  return resObj.count > obj.count ? resObj : obj
})
document.querySelector("pre").textContent =
  JSON.stringify(res, null, 4);
<pre></pre>

您可以使用.reduce而不是.map

const objects = [
  { username: 'mark', count: 3 },
  { username: 'dave', count: 5 },
  { username: 'lucy', count: 2 },
]
const max = objects.reduce((acc, obj) => (
  obj.count > acc.count ? obj : acc
))
console.log(max)

您可以首先找到计数的max,然后找到具有该计数的对象

var objects = {
    object1: {username: 'mark', count: 3},
    object2: {username: 'dave', count: 5},
    object3: {username: 'lucy', count: 2},
}, result = null;
var max = Math.max.apply(null, Object.keys(objects).map(e => {return objects[e].count}));
for (var obj in objects) {
  if (objects[obj].count == max) result = objects[obj];
}
console.log(result)

最新更新