Return object with default values from array in Javascript

后端 未结 4 453
离开以前
离开以前 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: ""}.

提交回复
热议问题