繁体   English   中英

JavaScript-使用唯一属性标识对象

[英]JavaScript - identify the object with a unique property

我设法从计数属性中识别出最高编号,但是我想记录与该编号关联的对象,即记录具有最高计数编号的对象。 我该怎么做呢?

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);

谢谢

代替.map() ,使用.reduce()获取所需的目标。

在这里,我返回结果对象的键。 您可以根据需要直接返回该对象。

 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) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM