0

I'm trying to have a configurable checkbox and want to have my array's values to be the keys for the object.

Given:

let colors = [red, blue, black, yellow, orange]

How do I make it so that it becomes:

colorChecklist = {
    red: true,
    blue: true,
    black: true,
    yellow: true,
    orange: true
}
G Josh
  • 271
  • 1
  • 5
  • 15

6 Answers6

3
const obj = {};
colors.forEach(c => obj[c] = true)

I know everybody likes reduce but it's unnecessarily complicated and well, see this and this

Kerim Güney
  • 1,059
  • 1
  • 10
  • 23
2

You can use reduce here .

One-liner

const colorChecklist = colors.reduce((acc, curr) => (acc[curr] = true, acc), {});

let colors = ["red", "blue", "black", "yellow", "orange"];

const colorChecklist = colors.reduce((acc, curr) => {
  acc[curr] = true;
  return acc;
}, {});

console.log(colorChecklist);
DecPK
  • 24,537
  • 6
  • 26
  • 42
2

Just use Array.prototype.reduce

const [red, blue, black, yellow, orange] = ["red", "blue", "black", "yellow", "orange"]

let colors = [red, blue, black, yellow, orange];

let colorChecklist = colors.reduce((acc, key) => (acc[key] = true, acc), {});

console.log(colorChecklist);
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
  • @FZs OP used identifiers in the creation of the `colors` array, not strings, so I did the same – Samathingamajig Oct 25 '21 at 05:59
  • I see now. I overlooked that thinking the OP meant strings, but forgot to add the quotes because of inexperience or lack of attention. – FZs Oct 25 '21 at 06:46
0

You can try to do a mass assignment (using an object method) to all of the properties since they are all boolean in type.

let colors = [true, true, true] // red, blue, green

var colorChecklist = {
    setValue: function( props, flag ) {
        while ( props.length ) this[ props.pop() ] = flag;
    }
}

colorChecklist.setValue( [...colors] , true );
netlemon
  • 964
  • 8
  • 22
0

You can use reduce() method.

const colorChecklist = colors.reduce((prev, curr) => ({ ...prev, [curr]: true }), {});
console.log(colorChecklist);
msrumon
  • 1,250
  • 1
  • 10
  • 27
-1

try with Array#Reduce

const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)
Moinul Robin
  • 36
  • 1
  • 10