Skip to content
Advertisement

Unable to use Computed Property Values with Dots – Unable to Set as String – JS

Example code: https://playcode.io/757707/

Take a look at what it is logging to the console. I am not sure if there is a way to compute property values, that have dots in the names, as valid JSON.

that third field in the objects that are printed is always:

{
    dot.notation: "value"
}

In order for it to be valid JSON you need quotes around the property name if you would like to have a dot “.” in the property name.

e.g. Valid JSON would look like this:

{
  "dot.notation": "value"
}

It seems it’s bad practice to use a dot in a property name… but there should be a way to set that property as a string explicitly so the JSON isn’t invalid if I compute the property name. Because of this parsing the JSON string of that JSON Object just doesn’t work.

Does anyone know of a workaround to explicitly set the property name in quotes?

I would love to just follow best practices and not use a dot in the property name but this is required for some requests in Looker. I was working for a client in Looker so I needed a workaround.

Advertisement

Answer

Strictly speaking of JSON format, ALL field names must be in quotes. This is required for interoperability, like sending data to a REST API, etc. Within these quotes, virtually any string is allowed per the JSON spec.

In JavaScript, this is looser, JavaScript objects don’t need quotes around property names when these names are simple (a-z, A-Z, 0-9, _, $), otherwise, quotes are needed to disambiguate for language parsing reasons.

IF you want a property to be set from a string value, just do this:

{
  [myStringVariable] : true
}

Without the need to fumble with quotes, this allows you to set a property with virtually any string. So you can set some constants in your code defining these field names, and then just do this in a consistent manner:

const FIELD1 = "my& crazy**field-name";  // Or from some schema definition.
// etc. other field consts.

let myObject = {
  [FIELD1] : true
  // .. etc.
}

Note also, that within this [ ] notation, you can put any valid JavaScript expression that can evaluate to a string, such as [myFields.field1Name] and even things like [(someCondition ? “unknown” : “myField”)]

Finally, none of this is any kind of “standard”, just mechanisms you may want to consider for cases where your field names are not controlled by you — because when they are controlled by you, you should keep them simple for clarity.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement