从Java数组中返回具有默认值的对象 [英] Return object with default values from array in Javascript
本文介绍了从Java数组中返回具有默认值的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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.
实际上我的情况是我想设置React组件的初始状态.
Actually my case is that I want to set 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,
};
...
预期结果将是
// state = {fields: {email: "", password: ""}}
推荐答案
每当您要将值数组简化为一个值时,都在寻找.reduce()
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]: ''}), {}),
};
这篇关于从Java数组中返回具有默认值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文