javascriptsyntactic-sugar

How can I elegantly check if any field has a longer value between two objects in JavaScript?


Consider:

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

I can write a lengthy for loop to do the job, but I am wondering: Is there an elegant way to check if any field has a length value (in the above example, item2's c is longer than item1's c) between two objects in JavaScript?


Solution

  • It's a pretty simple iteration over the Object.entries of one of the objects and doesn't seem lengthy at all:

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

    Or, to golf it more, but make it less readable, you can destructure the length property of the val1 immediately:

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