Reputation: 145
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?
Upvotes: 9
Views: 55685
Reputation: 3262
If you're googling this and want to know how to do this for types, you can use the (typeof x)[keyof typeof x]
pattern:
const VARIANTS_BY_ID = {
100: 'diagonal',
120: 'knight',
125: 'king',
200: 'disjointGroups',
300: 'consecutive',
} as const;
// type Variants = "diagonal" | "knight" | "king" | "disjointGroups" | "consecutive"
type Variants = (typeof VARIANTS_BY_ID)[keyof typeof VARIANTS_BY_ID];
Upvotes: 3
Reputation: 1
Well, any respose worked in my setup, so i tryed this:
let formattedData = {}
for (let index = 0; index < values.length; index++) {
eval("formattedData[indexToChar(index)] = values[index]");
}
basicaly it works because js understand it, but ts dont, so if i use eval ts dont try to parse and dont throw error, so js read it and excecute correctely. eval doc:
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/eval
Upvotes: 0
Reputation: 221
If you need the value of a specific key you can access it using the following method :
Object(nameofobj)["nameofthekey"]
Upvotes: 20
Reputation: 117
Just as an alternative. You also could use Object.getOwnPropertyNames()
let obj = {...};
Object.getOwnPropertyNames(obj).forEach(key => {
let value = obj[key];
});
Upvotes: 4
Reputation: 16779
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']
Upvotes: 9
Reputation: 12414
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.
Upvotes: 17