9

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: ""}}
3
  • fields will have only two values? Commented Jan 16, 2019 at 13:59
  • 4
    fields.reduce((acc,k) => (acc[k] = "", acc), {}) Commented Jan 16, 2019 at 14:01
  • @brk that is for simplicity purpose in question only Commented Jan 16, 2019 at 14:08

4 Answers 4

10

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]: ''}), {}),
};
Sign up to request clarification or add additional context in comments.

Comments

8

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

Comments

5

You could map objects and assign all to a single object.

const
    fields = ['email', 'password'],
    object = Object.assign({}, ...fields.map(key => ({ [key]: '' })));

console.log(object);

Comments

2

You need to transform your array which contains keys into a real object.

To do it, you have many possibilities, but you still have to do something. There isn't any magical trick.

My favorite solution is to use a function to insert into your utility class. So it's easy to read and reusable.


Number 1: The function

function initializeKeys(keys, initialValue, object) {
  return keys.reduce((tmp, x) => {
    tmp[x] = initialValue;

    return tmp;
  }, object);
}

const objFields = initializeKeys(['email', 'password'], '', {
  otherKey: 'a',
});

console.log(objFields);


Number 2: The forEach

const fields = ['email', 'password'];

const objFields = {};

fields.forEach(value => {
  objFields[value] = '';
});

console.log(objFields);


Number 3: The reduce

const fields = ['email', 'password'];

const objFields = {
  ...fields.reduce((tmp, x) => {
    tmp[x] = '';

    return tmp;
  }, {}),
};

console.log(objFields);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.