Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if object contains properties with value

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.

in C# using linq i could do something like: var x = SoftwareBadges.Where(c => c.Guid == test)

how can i do this in javascript ?

like image 625
Rafael Herscovici Avatar asked Jan 04 '12 13:01

Rafael Herscovici


People also ask

How do you know if an object has a property value?

The hasOwnProperty() method returns true if the specified property is a direct property of the object — even if the value is null or undefined . The method returns false if the property is inherited, or has not been declared at all.

How do you check if an object has a key value?

You can use the JavaScript in operator to check if a specified property/key exists in an object. It has a straightforward syntax and returns true if the specified property/key exists in the specified object or its prototype chain. Note: The value before the in keyword should be of type string or symbol .

How do you check if an object contains a property in Java?

JavaScript provides you with three common ways to check if a property exists in an object: Use the hasOwnProperty() method. Use the in operator. Compare property with undefined .


2 Answers

As associative array you can try this:

for (var s in SoftwareBadges) {
    if (SoftwareBadges[s]["Guid"] == "7e9")
       alert(SoftwareBadges[s]["Title"]);
}
like image 127
ciccioska Avatar answered Sep 28 '22 11:09

ciccioska


Array#filter may come handy

(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.

You may see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter for detailed document.

like image 42
qiao Avatar answered Sep 28 '22 10:09

qiao