1

I want to create this as end result: {"customerName: {"contains": "bri"}}, but I keep getting the name of the variable written instead. I've tried a multitude of things and just can't get it to go as I want. Hoping this is simple and I'm just completely overlooking it.

interface IGraphQLFilterVariable {
  [key: string]: [key: string] | any | IGraphQLFilterVariable[]
}
let property = "customerName";
let type = "contains";
let filter = "bri";

let singleFilter: IGraphQLFilterVariable = {};
singleFilter[property] = {
  type: filter
};
console.log(singleFilter);

Playground

Briana Finney
  • 1,171
  • 5
  • 12
  • 22
  • 2
    Please post your current code directly into your question body alongside the screenshot, it'll make it easier for folks to help you. – y2bd Mar 12 '21 at 21:06
  • Does this answer your question? [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal) – y2bd Mar 12 '21 at 21:11

1 Answers1

2

When defining objects, only the values of the objects are expressions by default. The keys are treated as strings, so when you go { type: filter }, it's essentially equivalent to { "type": filter }.

To use a variable's value as a the key of an object, surround the key in brackets:

singleFilter[property] = { [type]: filter };

Your object will then look up the value of the variable type and use that as the key for the object.

y2bd
  • 5,783
  • 1
  • 22
  • 25