Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to extract object values in Typescript

Tags:

javascript

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?

like image 234
David Carrick Sutherland Avatar asked Mar 31 '17 18:03

David Carrick Sutherland


3 Answers

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 your tsconfig.json. Make sure you are using a polyfill or if your final platform support this feature.

like image 164
Diullei Avatar answered Oct 25 '22 22:10

Diullei


If you need the value of a specific key you can access it using the following method :

Object(nameofobj)["nameofthekey"]
like image 36
Devashree Avatar answered Oct 25 '22 21:10

Devashree


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']
like image 9
gyre Avatar answered Oct 25 '22 22:10

gyre