Hola tengo el siguiente objeto que estoy reduciendo a la clave que su valor es el mayor:
project.approved_account_ids: { "sp02.testnet": 3, "sp03.testnet": 1 }Al igual que..
<Typography variant="body2"> Architect: {Object.keys(project.approved_account_ids).reduce((a, b) => project.approved_account_ids[a] > project.approved_account_ids[b] ? a : b)} </Typography>}Pero si el objeto es como
project.approved_account_ids: {}Recibo el error - TypeError: Reducir la matriz vacía sin valor inicial. Lo cual sé que es porque no siempre hay claves y valores para reducir.
Intenté agregar un valor inicial al final como
{Object.keys(project.approved_account_ids).reduce((a, b) => project.approved_account_ids[a] > project.approved_account_ids[b], 0 ? a : b)}Pero eso no funciona. ¿Cuál sería el mejor método para verificar si hay valores en primer lugar antes de aplicar reduce ()? ¡¡Cualquier ayuda sería apreciada!!
Suponiendo que solo desea el valor más alto, ¿entonces solo el número real?
Object.entries() usado en el objeto que se encuentra aquí: obj.project.approved_account_ids Object.entries(obj).reduce( // Obj is now an array of pairs: [[key, val], [key, val],...]["key",-1] y luego compare eso inicialmente, que por supuesto se reemplazará en la primera iteración: (max, [key, val]) => max[1] > val ? max : [key, val], ["key", -1] // Note the second param is destructured to a pair [key, val]output[1] En lo que respecta a un objeto vacío o sin valores numéricos, no fallará, devolverá -1 en su lugar, vea objB en el ejemplo. Además, Object.values() también funciona, pero optó por Object.entries() en caso de que la clave real también sea importante.
const obj = { project: { approved_account_ids: { "sp02.testnet": 3, "sp03.testnet": 1, "sp00.testnet": null, "sp04.testnet": 5, "sp05.testnet": 3 }, pending_account_ids: {} } }; const objA = obj.project.approved_account_ids; const objB = obj.project.pending_account_ids; function maxV(obj) { let output = Object.entries(obj).reduce( (max, [key, val]) => max[1] > val ? max : [key, val], ["key", -1] ) return output; } console.log('Returning the highest number: maxV(objA)[1]'); console.log(maxV(objA)[1]); console.log('Returning from an empty object: maxV(objB)[1]'); console.log(maxV(objB)[1]); console.log('Returning the key of the highest number: maxV(objA)[0]'); console.log(maxV(objA)[0]); console.log('Returning the key and the highest number as an array: maxV(objA)'); console.log(maxV(objA)); console.log('Returning the key and the highest number as an object: Object.fromEntries([[...maxV(objA)]])'); console.log(Object.fromEntries([[...maxV(objA)]]));