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
}
2
  • Does this answer your question? Convert Array to Object Commented Oct 25, 2021 at 5:56
  • @TBA That's way different than this question Commented Oct 25, 2021 at 5:57

6 Answers 6

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

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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);

2 Comments

@FZs OP used identifiers in the creation of the colors array, not strings, so I did the same
I see now. I overlooked that thinking the OP meant strings, but forgot to add the quotes because of inexperience or lack of attention.
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 );

Comments

0

You can use reduce() method.

const colorChecklist = colors.reduce((prev, curr) => ({ ...prev, [curr]: true }), {});
console.log(colorChecklist);

Comments

-1

try with Array#Reduce

const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)

2 Comments

This sets each value to an empty string, not true
@Samathingamajig I have just given an example of how you can use array Reduce, you can always configure the value the way you want.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.