减少以在提供初始值的同时返回特定值

西蒙·帕尔默

嗨,我有以下对象,我将其简化为它的值最大的关键:

project.approved_account_ids: {
    "sp02.testnet": 3,
    "sp03.testnet": 1
}

像这样。。

<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>}

但是如果对象像

project.approved_account_ids: {}

我收到错误-TypeError:减少没有初始值的空数组。我知道这是因为并不总是需要减少键和值。

我尝试在最后添加一个初始值,例如

{Object.keys(project.approved_account_ids).reduce((a, b) => project.approved_account_ids[a] > project.approved_account_ids[b], 0 ? a : b)}

但这不起作用。在应用reduce()之前首先检查是否有值的最佳方法是什么?任何帮助,将不胜感激!!

ze00ne

假设您只想要最高值,那么只是实际数字?

  • 用于Object.entries()此处找到的对象:obj.project.approved_account_ids
Object.entries(obj).reduce(
// Obj is now an array of pairs: [[key, val], [key, val],...]
  • 接下来将初始值设置为假对:["key",-1]然后比较最初在第一次迭代中当然会被替换的值:
(max, [key, val]) =>
    max[1] > val ? max : [key, val], ["key", -1]
// Note the second param is destructured to a pair [key, val]
  • 返回最高对的第二个值:output[1]

对于空对象或没有数字值,它不会失败,而是返回 -1,参见objB示例。此外,也Object.values()可以正常工作,但Object.entries()为了以防万一实际关键也很重要。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章