我正在尝试一个可配置的复选框,并希望将数组的值作为对象的键。
给定:
let colors = [red, blue, black, yellow, orange]
我如何使它成为:
colorChecklist = {
red: true,
blue: true,
black: true,
yellow: true,
orange: true
}
const obj = {};
colors.forEach(c => obj[c] = true)
我知道每个人都喜欢减少,但这是不必要的复杂和好,看看这个和这个
您可以在此处使用reduce。
一行
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);
只需使用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);
您可以尝试对所有属性进行批量赋值(使用对象方法),因为它们的类型都是布尔值。
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 );
您可以使用reduce()
方法。
const colorChecklist = colors.reduce((prev, curr) => ({ ...prev, [curr]: true }), {});
console.log(colorChecklist);
尝试使用Array#Reduce
const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)