Javascript TypeScript:在对象中查找键/值(列表理解?)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38292652/
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
TypeScript: Find Key / Value in Object (list comprehension?)
提问by stevek
How to do find index==2
in TypeScript?
如何index==2
在 TypeScript 中查找?
myObj = {
policy : {
index: 1,
page : "/summer"
},
purchase : {
index: 2,
page : "/sun"
}
}
E.g.
例如
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
if (myObj[key].index === 2)
console.log("Found.");
}
}
How to do this in JS or TS more efficiently?
如何更有效地在 JS 或 TS 中做到这一点?
回答by Nitzan Tomer
Javascript-wise I'd use the Object.keys()function:
Javascript-wise 我会使用Object.keys()函数:
Object.keys(myObj).forEach(key => {
if (myObj[key].index === 2) {
console.log("Found.");
}
});
Because it removes the need to check myObj.hasOwnProperty(key)
.
因为它不需要检查myObj.hasOwnProperty(key)
.
If you want to stop the search when one was found:
如果您想在找到时停止搜索:
Object.keys(myObj).some(key => myObj[key].index === 2);
回答by Nitzan Tomer
Use Array.find
:
使用Array.find
:
Object.keys(myObj).find(k => myObj[k].index === 2)
This will return the key in which the match occurred.
这将返回匹配发生的键。