Consider:
const fields = ['email', 'password'];
const objFields = {};
fields.forEach(value => {
objFields[value] = '';
});
console.log(objFields);
// Outputs {email: "", password: ""}
I want to achieve the same result, but without having to initialize an empty object.
Actually, my case is that I want to set the initial state of a React component.
class App extends Component {
fields = ['email', 'password'];
state = {
fields: // The one liner code here that should return the object created from fields array,
};
...
The expected result would be
// state = {fields: {email: "", password: ""}}
fieldswill have only two values?fields.reduce((acc,k) => (acc[k] = "", acc), {})