Return object with default values from array in Javascript

后端 未结 4 455
离开以前
离开以前 2021-01-22 14:10
    const fields = [\'email\', \'password\'];

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

    console.log(objFiel         


        
相关标签:
4条回答
  • 2021-01-22 14:21

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

    0 讨论(0)
  • 2021-01-22 14:30

    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]: ''}), {}),
    };
    
    0 讨论(0)
  • 2021-01-22 14:42

    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);

    0 讨论(0)
  • 2021-01-22 14:43

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

    To do it you have many possibilites, but you still have to do something, there is no magical trick.

    My favorite soluce is to use a function to insert into your Utilitary class. So it's easy to read and re-usable.


    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);

    0 讨论(0)
提交回复
热议问题