skip to Main Content

I have an "required" list of headers in an array that I am wanting to check an object of headers against.

My aim is to get a list of the headers that are missing.

I am wanting this to be case-insensitive.

// For example:

const masterHeads = ['head1', 'head2', 'Head3'];
const headers = {
  Heasd1: 'xxx',
  Head2: 'yyy',
  Head3: 'zzz',
  other: 'blah'
};

// output: [ head1 ]

I have so far devised

masterHeads.filter(master => !headers?.[master.toLowerCase()]);

but this seems to be case-sensitive.

2

Answers


  1. Chosen as BEST ANSWER

    UPDATE: This isn't the answer but is perhaps a step to finding it... This does the filtering to find which header(s) are missing, but returns them in lowercase and not in their original case.


    I believe I found the answer after thinking about it for a bit longer.

    I essentially map each array of the accepted and the header keys to lowercase entirely, then do a check to see if the headers includes the master headers

    const lowerHeads = Object.keys(headers).map(head => head.toLowerCase());
    const master = masterHeads.map(head => head.toLowerCase());
    const res = master.filter(m => !lowerHeads.includes(m));
    

  2. You could take a Set of normalized strings and check against in the filter.

    const
        masterHeads = ['head1', 'head2', 'Head3'],
        headers = { Heasd1: 'xxx', Head2: 'yyy', Head3: 'zzz', other: 'blah' },
        keys = new Set(Object.keys(headers).map(s => s.toLowerCase())),
        result = masterHeads.filter(master => !keys.has(master.toLowerCase()));
    
    console.log(result); // ['head1']
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search