How can i get object with highest value?
I have this nested objects
var obj = {
first:{
num:10
},
second: {
num:5
},
third: {
num: 15
}
}
console.log(obj);
so there could be a lot of nested objects inside and i need to get the object with highest num
value inside which in this case is the third
object.
So i should get as output
third: {
num: 15
}
I got stuck at the iteration
var arr = Object.keys( obj ).map(function ( key, index ) {
console.log(obj[key]);
});
console.log(arr);
If you want the whole object back with the high value, I would use 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);
as I mentioned in my comment above, what you mentioned as expected output is not really an object. however, you can use following snippet to find the key within ur main object which holds the highest num:
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 }