Array to flags object

Angelos Chalaris · JavaScript, Array, Object · Apr 12, 2022

Converts an array of strings into an object mapping to true.

  • Use Array.prototype.reduce() to convert the array into an object, where each array value is used as a key whose value is set to true.
const flags = arr => arr.reduce((acc, str) => ({...acc, [str]: true }), {});
flags(['red', 'green']); // { red: true, green: true }

Recommended snippets

  • JSON to CSV

    JavaScript, Array

    Converts an array of objects to a comma-separated values (CSV) string that contains only the columns specified.

  • Creates an object from an array, using a function to map each value to a key.

  • Map array to object

    JavaScript, Array

    Maps the values of an array to an object using a function.