Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return object with default values from an array in JavaScript

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: ""}}
like image 789
Raheel Avatar asked May 08 '26 11:05

Raheel


2 Answers

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]: ''}), {}),
};
like image 186
Madara's Ghost Avatar answered May 11 '26 00:05

Madara's Ghost


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: ""}.

like image 38
Matt Janssen Avatar answered May 11 '26 00:05

Matt Janssen