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

2
  • 2
    Please post your current code directly into your question body alongside the screenshot, it'll make it easier for folks to help you. Commented Mar 12, 2021 at 21:06
  • Does this answer your question? How to use a variable for a key in a JavaScript object literal? Commented Mar 12, 2021 at 21:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.