簡體   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