Home > Back-end >  Better way to turn object with named booleans into array with their uppercase keys?
Better way to turn object with named booleans into array with their uppercase keys?

Time:06-25

I'm trying to convert the methods part of an Express Router into a one-dimensional array of uppercase string words, so this:

layer.route.methods: { get: true, post: true }

into:

methods: ["GET", "POST"]

This is what I came up with, but isn't there a more subtle way?

const methods = [];
!layer.route.methods.get || methods.push('GET');
!layer.route.methods.post || methods.push('POST');

CodePudding user response:

This can be achieved with a combination of filter (to get only the methods with true) and map (to capitalize).

const methods = { get: true, post: true };

const result = Object.keys(methods).filter(method => methods[method]).map(method => method.toUpperCase());

console.log(result);

CodePudding user response:

Turn down object to an array by using Object.keys(object) and then use loop either for or map to iterate and check if item exist in that converted array convert then to uppercase using item.toUpperCase()

CodePudding user response:

One of the ways is to use reducer, to filter and modify values in one iteration.

const inputObject = { get: true, post: true };

const methods = Object.entries(inputObject).reduce(
  (accumulator, [key, value]) => {
    if (value) accumulator.push(key.toUpperCase());
    return accumulator;
  },
  []
);

console.log(methods);

  • Related