简体   繁体   English

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

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

I have managed to identify the highest number out of the count properties however I want to log the object associated with that number, ie log the object with the highest count number. 我设法从计数属性中识别出最高编号,但是我想记录与该编号关联的对象,即记录具有最高计数编号的对象。 How do I do this? 我该怎么做呢?

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

Thanks 谢谢

Instead of .map() , use .reduce() to get the desired target. 代替.map() ,使用.reduce()获取所需的目标。

Here I'm returning the key of the result object. 在这里,我返回结果对象的键。 You could return the object directly if you wish. 您可以根据需要直接返回该对象。

 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> 


If objects was meant to be an Array, you can still use .reduce() , just without Object.keys() . 如果objects原本是一个数组,则仍然可以使用.reduce() ,而无需使用Object.keys() This returns the objects directly, which was alluded to in the first solution. 这将直接返回对象,这在第一个解决方案中已经提到过。

 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> 

You could use .reduce instead of .map . 您可以使用.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)

You can first find max of count and then find object with that count 您可以先找到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