I have been trying to convert a JavaScript web form to Typescript, and have been unable to work out how to deal with the following (which works in JavaScript):
let fieldValues = JSON.parse(cookieData);
let keys = Object.keys(fieldValues);
let values = Object.values(fieldValues);
Visual Studio tells me:
Error TS2339 Property 'values' does not exist on type 'ObjectConstructor'.
What can I do?
The Object.values(..)
is not stabilized, so it is unsupported in many browsers (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values)
Use map
instead:
let values = Object.keys(fieldValues).map(key => fieldValues[key]);
If you really want to use this function you need to add the
"es2017.object"
lib on yourtsconfig.json
. Make sure you are using a polyfill or if your final platform support this feature.
If you need the value of a specific key you can access it using the following method :
Object(nameofobj)["nameofthekey"]
If Object.values
is not supported (which today is often the case), you can just map
over your keys
:
let cookieData = '{"key":"value"}'
let fieldValues = JSON.parse(cookieData)
let keys = Object.keys(fieldValues)
let values = keys.map(k => fieldValues[k])
console.log(keys) //=> ['key']
console.log(values) //=> ['value']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With