With this code i want to achieve output name: Gunnar
but I get { name: 'Gunnar' }
, how do I remove the ''
around Gunnar in the output?
let keyName = "name";
let value = "Gunnar";
let person = {
[keyName]: value
};
console.log(person)
I’ve guess it have something to do with the "value" but i can’t figure out how to fix it.
2
Answers
You can overwrite
console.log
so it removes"
when printingYour code outputs an object using
console.log
. Theconsole.log
function will output it in the standard format for outputting objects in your environment. Nothing in your code is designed to create the output you want.If you want the output
name: Gunnar
, then you need to change yourconsole.log
statement so you’re outputting that text, rather than telling it to output an object, for instance:If you need
person
to be your starting point, but you still have access tokeyName
, then you can do it with dynamic property access, like this:If you don’t want to use
keyName
orvalue
, then it’s not clear what you do want to do. Maybe you want to output multiple lines for each property:Or maybe you’re expecting an object with exactly one property (although doing that without knowing what the property name is isn’t generally good practice):
More to explore:
for-in
loopObject.keys