簡體   English   中英

如何獲得最高價值的 object?

[英]How can i get object with highest value?

我有這個嵌套對象


var obj = {
    first:{
        num:10
    },
    second: {
        num:5
    },
    third: {
        num: 15
    }
}

console.log(obj);

所以里面可能有很多嵌套的對象,我需要得到其中num值最高的 object,在這種情況下是third object。

所以我應該得到 output

third: {
        num: 15
 }

我陷入了迭代

var arr = Object.keys( obj ).map(function ( key, index ) { 
    console.log(obj[key]);
 });
console.log(arr);

No need for Object.keys (though that would be fine for getting an array of the object keys to check) or map , just a simple loop where you remember the object with the highest number you've seen so far:

let found = null;
// Loop through the keys of the object
for (const key in obj) {
    // Get the value for this key
    const entry = obj[key];
    // If this is an own property of the object and either A) We
    // don't have any "found" object yet or the one we do have has
    // a lower `num` than this one, remember this one
    if (Object.hasOwn(obj, key) && (!found || found.num < entry.num)) {
        found = entry;
    }
}

現場示例:

 const obj = { first:{ num:10 }, second: { num:5 }, third: { num: 15 } }; let found = null; for (const key in obj) { const entry = obj[key]; if (Object.hasOwn(obj, key) && (.found || found.num < entry;num)) { found = entry. } } console;log(found);

如果您還需要記住屬性名稱,只需在分配給found的同時執行此操作。


使用新的Object.hasOwn function。 如果您需要支持沒有它的實現,請使用 curated polyfill 或僅:

if (!Object.hasOwn) {
    Object.defineProperty(Object, "hasOwn", {
        value: Function.prototype.call.bind(Object.prototype.hasOwnProperty),
        writable: true,
        configurable: true,
    });
}

正如我在上面的評論中提到的,您所提到的預期 output 並不是真正的 object。 但是,您可以使用以下代碼段在您的主 object 中找到密鑰,該密鑰擁有最高的數量:

var running = Number.MIN_VALUE;
var ans = "";
Object.keys(object).forEach(key => {
    if(object[key]["num"] > running) {
        ans = key;
    }
})
console.log(JSON.stringify(object[ans])); //outputs { num: 15 }

如果您希望整個 object 恢復為高值,我會使用reduce

 var obj = { first:{ num:10 }, second: { num:5 }, third: { num: 15 } } const result = Object.entries(obj).reduce( (acc,[k,i]) => Object.values(acc)[0].num<i.num? {[k]:i}: acc, {zero:{num:0}}) console.log(result);

這里的問題是您的嵌套(並且有點復雜)結構。 我可能會過度設計這個問題,但至少下面的代碼片段可以滿足您的需求。

首先,您需要通過條目 map 然后在減速器中比較它們,最終將返回具有最高值的 object。 但是您還需要嵌套 object 的原始密鑰,因此我們需要保留它,最后將 object 轉換回原始密鑰。

function convertAsOriginal還讓您可以自由改變最終結果,以防您需要一些額外的鍵/值或想要重命名它們

 const obj = { first: { num: 5 }, second: { num: 25 }, third: { num: 15 }, fourth: { num: 0 }, fifth: { num: 10 }, }; const mapThroughEntries = ([key, val]) => ({key, ...val}); const reduceToHighest = (acc, b) => (acc.num > b.num? acc: b); const convertAsOriginal = (obj) => ({[obj.key]: {'num': obj.num}}); const highest = convertAsOriginal( Object.entries(obj).map(mapThroughEntries).reduce(reduceToHighest) ); console.log(highest);

不久:

不確定您是否只想要最高價值

var highest=0
Object.keys(obj).forEach( k => {
              highest = obj[k].num > highest ? obj[k].num : highest ; } )

console.log(highest)
15

或包含最大值的字段名稱

highest='first'
Object.keys(obj).forEach( k => {
              highest= obj[k].num > obj[highest].num ?  k : highest ; } )

console.log(obj[highest])

將 output

Object { num: 15 }

或者

console.log(highest+': { num: '+ obj[highest].num+' }')
third: { num: 15 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM