What is a more compact way to convert color=["red", "green", "blue", "Other"]
into colorObjFinal = { blue: true, green: true, Other: "Other", red: true }
?
This is my long function, I would like to shorten it:
let color = ["red", "green", "blue", "Other"];
let colorObj;
let colorObjFinal = {};
console.log("color:", color);
colorObj = color.reduce((a, v) => ({
...a,
[v]: v
}), {});
console.log("colorObj:", colorObj)
for (var key in colorObj) {
if (colorObj.hasOwnProperty(key)) {
if(key == 'Other'){
colorObjFinal[key] = colorObj[key];
} else {
colorObjFinal[key] = true;
}
}
}
console.log("colorObjFinal:", colorObjFinal)
You could just do it all in 1 go:
let color = ["red", "green", "blue", "Other"];
let result = color.reduce ((a,v) => ({
...a,
[v] : v == "Other" ? v : true
}),{});
console.log(result);
You can change your first Array.reduce
to get the result.
let color = ["red", "green", "blue", "Other"];
const result = color.reduce((acc, item) => {
acc[item] = (item != "Other") ? true : item;
return acc;
}, {});
console.log(result);
that ? (is arguably the most compact writing here)
let color = ["red", "green", "blue", "Other"];
const res = color.reduce((a,c)=>(a[c]=c=='Other'?c:true,a),{});
console.log(res);