JS 中如何优雅地检查两个对象之间是否有字段具有更长的值?

How to elegantly check if any field has a longer value between two objects in JS?

item1 = {a:[1], b:[2], c:[3]}
item2 = {a:[1], b:[2], c:[3,4]}

我可以编写一个冗长的 for 循环来完成这项工作,但我想知道:是否有一种优雅的方法来检查是否有任何字段具有长度值(在上面的示例中,item2citem1c)长于两个对象之间的JS?

这是对其中一个对象的 Object.entries 的非常简单的迭代,看起来一点也不冗长:

// assuming that both objects will contain the same keys:
const item1 = {a:[1], b:[2], c:[3]};
const item2 = {a:[1], b:[2], c:[3,4]};

const anyInItem2Bigger = Object.entries(item1)
  .some(([key, val1]) => item2[key].length > val1.length);
console.log(anyInItem2Bigger);

或者,为了让它更有趣但更难读,您可以立即解构 val1length 属性:

// assuming that both objects will contain the same keys:
const item1 = {a:[1], b:[2], c:[3]};
const item2 = {a:[1], b:[2], c:[3,4]};

const anyInItem2Bigger = Object.entries(item1)
  .some(([key, { length }]) => item2[key].length > length);
console.log(anyInItem2Bigger);

只是 CertainPerformance 出色解决方案的替代方案,正如有人建议我将其发布到另一个答案中一样。

它只是使用 Object.keys instead of Object.entries,虽然 99% 相同,但看起来可能更干净一些:

const item1 = {a:[1], b:[2], c:[3]};
const item2 = {a:[1], b:[2], c:[3,4]};

const anyInItem2Bigger = Object.keys(item1)
  .some(key => item2[key].length > item1[key].length);

要添加一些更有价值的东西,如果您需要检索具有较长项目的实际键列表,您可以使用 Array.reduce:

const item1 = {a:[1], b:[2], c:[3]};
const item2 = {a:[1], b:[2], c:[3,4]};
    
const longerKeysInItem2 = Object.keys(item1)
  .reduce((lk, key) => item2[key].length > item1[key].length ? [...lk, ...[key]] : lk, []);
  
console.log(longerKeysInItem2);