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: ""}}
Whenever you're looking for reducing an array of values to one value, you're looking for .reduce():
state = {
fields: fields.reduce((acc, key) => ({...acc, [key]: ''}), {}),
};
In modern browsers, or by using polyfills, you can use Object.fromEntries() to create an object from an array, using the array's values as keys/properties, and fill the object's values with a default.
const fields = ['email', 'password'];
const result = Object.fromEntries(fields.map(value => [value, '']));
The result is {email: "", password: ""}.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With