typescript 无法在打字稿中提取对象值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43147696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unable to extract object values in Typescript
提问by David Carrick Sutherland
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):
我一直在尝试将 JavaScript 网络表单转换为 Typescript,但一直无法解决以下问题(在 JavaScript 中有效):
let fieldValues = JSON.parse(cookieData);
let keys = Object.keys(fieldValues);
let values = Object.values(fieldValues);
Visual Studio tells me:
Visual Studio 告诉我:
Error TS2339 Property 'values' does not exist on type 'ObjectConstructor'.
错误 TS2339 类型“ObjectConstructor”上不存在属性“values”。
What can I do?
我能做什么?
回答by Diullei
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)
在Object.values(..)
没有稳定,所以它不支持在许多浏览器(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values)
Use map
instead:
使用map
来代替:
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.
如果你真的想使用这个功能,你需要
"es2017.object"
在你的tsconfig.json
. 确保您使用的是 polyfill,或者您的最终平台是否支持此功能。
回答by gyre
If Object.values
is not supported (which today is often the case), you can just map
over your keys
:
如果Object.values
不支持(今天经常是这种情况),你可以只map
在你的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']
回答by Devashree
If you need the value of a specific key you can access it using the following method :
如果您需要特定键的值,您可以使用以下方法访问它:
Object(nameofobj)["nameofthekey"]
回答by stefku
Just as an alternative. You also could use Object.getOwnPropertyNames()
只是作为替代。你也可以使用Object.getOwnPropertyNames()
let obj = {...};
Object.getOwnPropertyNames(obj).forEach(key => {
let value = obj[key];
});