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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:22:59  来源:igfitidea点击:

check if object contains properties with value

javascriptarraysjson

提问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 PlayTechObject.

如何获取包含此 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#filtermay come handy

Array#filter可能会派上用场

(SoftwareBadges.filter(function(v) {
  return v['Guid'] == '7e9';
}))[0]

Note that filteris 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了解详细文档。