javascript 检查对象是否包含具有值的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8727857/
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
check if object contains properties with value
提问by Dementic
i have the following array:
我有以下数组:
SoftwareBadges =
[
{ Title: "Playtech", Guid: "7e9", xPos: "96" },
{ Title: "BetSoft", Guid: "890", xPos: "169" },
{ Title: "WagerWorks", Guid: "35c", xPos: "242" },
{ Title: "Rival", Guid: "c35", xPos: "314" },
{ Title: "NetEnt", Guid: "59e", xPos: "387" },
{ Title: "MicroGaming", Guid: "19a", xPos: "460" },
{ Title: "Cayetano", Guid: "155", xPos: "533" },
{ Title: "OpenBet", Guid: "cfe", xPos: "607" },
{ Title: "RTG", Guid: "4e6", xPos: "680" },
{ Title: "Cryptologic", Guid: "05d", xPos: "753" },
{ Title: "CTXM", Guid: "51d", xPos: "827" },
{ Title: "Sheriff", Guid: "63e", xPos: "898" },
{ Title: "Vegas Tech", Guid: "a50", xPos: "975" },
{ Title: "Top Game", Guid: "0d0", xPos: "1048" },
{ Title: "Party Gaming", Guid: "46d", xPos: "1121" }
]
now, i need to check if on of them contains a value, and return the object for example:
现在,我需要检查它们中是否包含一个值,并返回对象,例如:
var test = "7e9" // Guid
how do i get the object that contains this Guid value ?
in the sample , it should return the PlayTech
Object.
如何获取包含此 Guid 值的对象?在示例中,它应该返回PlayTech
对象。
in C# using linq i could do something like:
var x = SoftwareBadges.Where(c => c.Guid == test)
在 C# 中使用 linq 我可以执行以下操作:
var x = SoftwareBadges.Where(c => c.Guid == test)
how can i do this in javascript ?
我怎样才能在 javascript 中做到这一点?
回答by ciccioska
As associative array you can try this:
作为关联数组,您可以尝试以下操作:
for (var s in SoftwareBadges) {
if (SoftwareBadges[s]["Guid"] == "7e9")
alert(SoftwareBadges[s]["Title"]);
}
回答by qiao
Array#filter
may come handy
Array#filter
可能会派上用场
(SoftwareBadges.filter(function(v) {
return v['Guid'] == '7e9';
}))[0]
Note that filter
is a part of ECMA5 and may not be available in some browsers.
请注意,它filter
是 ECMA5 的一部分,在某些浏览器中可能不可用。
You may see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filterfor detailed document.
您可以查看https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter了解详细文档。