Search code examples
javascriptobjectpropertiesnaming

dot character in property name


I got this code snippet from jest documentation. In the example, one of the variables is named ceiling.height and is the only variable with a dot . in the name. What would be the purpose of using variables with a dot in the name such that it warrants this example in the documentation?

  const houseForSale = {
    bath: true,
    bedrooms: 4,
    kitchen: {
      amenities: ['oven', 'stove', 'washer'],
      area: 20,
      wallColor: 'white',
      'nice.oven': true,
    },
    'ceiling.height': 2,
  };

Solution

  • The purpose would be to store nested objects in a flat format, ie. a database table. You could use something like dottie.js to transform this flat object into a nested object

    const values = {
      'user.name': 'Gummy Bear',
      'user.email': 'gummybear@candymountain.com',
      'user.professional.title': 'King',
      'user.professional.employer': 'Candy Mountain'
    };
    const transformed = dottie.transform(values);
    

    We would now find this to be the value of transformed

    {
      user: {
        name: 'Gummy Bear',
        email: 'gummybear@candymountain.com',
        professional: {
          title: 'King',
          employer: 'Candy Mountain'
        }
      }
    }
    

    Why they use it like that in the example seems to be so that they can provide an example (below) on how to access these kinds of variable names. Imagine that you wanted the .toHaveProperty(keyPath value?) function from the Jest docs to operate on a property in the values object from the above example. This shows you how you might use this function with such a property.

    // Referencing keys with dot in the key itself
    expect(houseForSale).toHaveProperty(['ceiling.height'], 'tall');
    

    Unless you have a very good reason, using these kinds of variable names is not a best practice and I would not recommend it. That said, while a variable name with a . character is not able to be used with dot syntax:

    houseForSale.ceiling.height = undefined
    

    It is still accessible with bracket syntax:

    houseForSale['ceiling.height'] = 2