Search code examples
javascriptobjectecmascript-6ecmascript-2016

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


So in my React project, I have a fallback default state for an address form that looks like this:

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

However, it feels quite ridiculous defining such a large object with all keys equal to null. Is there a shorter way of doing this? Something in ES6/ES7?


Solution

  • You could use an array and iterate the keys and build a new object with 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; }