0

I am trying to create an object in typescript that has a string key and a string value.

const titleValue: string = "key";

const objectINeed = {
    titleValue: 'value'
};

console.log(JSON.stringify(objectINeed))

This prints

"{"titleValue":"value"}"

I instead want this to return {"key" : "value"}

TS Play link

I am not able to understand why the titleValue variable's stored value is not being picked up. Apologies if the title of the question is making it difficult to understand. I did not have better words for my problem as I am quite new to typescript and javascript.

0

1 Answer 1

2

Put the titleValue in [] parantheses, so it uses the value of titleValue as key instead of the word titleValue:

const titleValue: string = "key";

const objectINeed = {
    [titleValue]: 'value'
};

console.log(JSON.stringify(objectINeed))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Why does it happen like this though - treat an existing variable like a string. This is quite confusing.
You assumption that this syntax should treat the property name as a variable is simply wrong. This works like this in some other languages, but not in javascript. You can read more on object initializers here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… especially the part about: "Computed property names".

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.