实例化每个键都等于 null 的对象的最佳方法?

Best way to instantiate an object with every key equal to null?

所以在我的 React 项目中,我有一个地址表单的回退默认状态,如下所示:

state = {
  newLocation: this.props.location || {
    lat: null,
    lng: null,
    street: null,
    complement: null,
    neighbourhood: null,
    city: null,
    state: null,
    zipCode: null,
    country: null,
  },
}

但是,定义这么大的对象,所有键都为null,感觉很可笑。有没有更短的方法来做到这一点? ES6/ES7?

中的内容

使用 defaultProps 方法

defaultProps can be defined as a property on the component class itself, to set the default props for the class. This is used for undefined props, but not for null props. For example:

class CustomButton extends React.Component {
  // ...
}

CustomButton.defaultProps = {
  color: 'blue'
};

您可以使用数组并迭代键并使用 Object.assign 构建一个新对象。

var keys = ['lat', 'lng', 'street', 'complement', 'neighbourhood', 'city', 'state', 'zipCode', 'country'],
    loc = { lat: 123, lng: 246, city: 'NY', country: 'USA' },
    state = {
        newLocation: Object.assign(keys.reduce((o, k) => Object.assign(o, { [k]: null }), {}), loc)
    };

console.log(state);
.as-console-wrapper { max-height: 100% !important; top: 0; }