Search code examples
javascriptobject

Javascript check if two objects are of equal lengths for all keys


Suppose I have two mappings:

const mapOne = {idOne: ['a', 'b'], idTwo: ['c', 'd', 'e']};
const mapTwo = {idOne: [1, 2], idTwo: [3, 4, 5]};

It should return true since both idOne has length 2 and idTwo has length 3. I tried doing:

const b = Object.entries(mapOne).map((k, v) => v.length === mapTwo[k].length);

But it's saying k is not defined and also it would return an array of boolean instead of a single boolean.


Solution

  • Use Object.entries and check if each of the [key, value] entries has equal length in both objects.

    The main problem in your code was that you should have written ([k,v]) instead of (k,v). Then, you need to use every instead of map.

    const mapOne = {idOne: ['a', 'b'], idTwo: ['c', 'd', 'e']};
    const mapTwo = {idOne: [1, 2], idTwo: [3, 4, 5]};
    
    const result = Object.entries(mapOne)
      .every(([k, {length}]) => mapTwo[k].length===length)
    
    console.log(result);