0

Working on a piece of code this happened to me:

async function getStatusesListForFilter(statusesToFilter, allStatuses) {
  const arrayOfStatuses = Array.isArray(statusesToFilter)
    ? statusesToFilter
    : statusesToFilter
        .split(',')
        .filter(item => item !== '')
        .map(item => item.trim());

  const filterOptions = {
    Active: DELIVERIES.ACTIVE_STATUSES,
    Inactive: DELIVERIES.INACTIVE_STATUSES,
    All: allStatuses.map(status => status.name),
  };

  return filterOptions[arrayOfStatuses] || arrayOfStatuses;
}

Can anybody explain why does this work?

return filterOptions[arrayOfStatuses] || arrayOfStatuses;

This is basically doing this filterOptions[['Any Value']] and it works!

Thanks in advance, it seems that the object parses whatever you pass between [] as a string.

Scarecrowsama
  • 345
  • 1
  • 3
  • 8
  • can you add what does those values look like? (like a dummy data or something) – I am L Oct 29 '19 at 11:19
  • 2
    That's not an "array value" it's a property name. – Quentin Oct 29 '19 at 11:19
  • So do objects take the value as a string even though it is an array? – Scarecrowsama Oct 29 '19 at 11:20
  • `[]` is called dynamic property accessing or Dot notation – Code Maniac Oct 29 '19 at 11:20
  • This code looks like bad practice, but it certainly can work. Yes, property access results in [toPropertyKey](https://tc39.es/ecma262/#sec-topropertykey), which will (apart from symbols) try to convert to string (and throw if unable to). – ASDFGerte Oct 29 '19 at 11:26
  • @ASDFGerte could you provide an alternative that is not a bad practice? – Scarecrowsama Oct 29 '19 at 11:37
  • It may or may not be bad practice, depending on the circumstances. However, not even having a comment, above a line that implicitly converts an array to string, is very fishy. If this isn't some internal code with a very clear input, I'd have to think for a while, what kinds of "accidental changes" could mess up this conversion. E.g. `Array.prototype.toString` searches for a callable property `join` - not even speaking of the conversion to string of all the array elements. – ASDFGerte Oct 29 '19 at 11:47

0 Answers0