How about using .hasOwnProperty() when working with objects and trying to find a key, the hasOwnProperty() method returns a boolean indicating whether the object has the specified property as own (not inherited) property. This method can be used to determine whether an object has the specified property as a direct property of that object unlike the in operator, this method does not check down the object's prototype chain.
Then you can use Array.prototype, to define your prototype for your array. The Array.prototype property represents the prototype for the Array constructor and allows you to add new properties and methods to all Array objects.
I updated your function as follows, hope it helps.
var arrayC = [{
name: "omer",
age: 16,
city: "pakistan"
},
{
name: "ali",
age: 26,
city: "pakistan"
}
];
// If JavaScript doesn't provide a assoc_search() method natively,
if (!Array.prototype.assoc_search) {
// returns after finding the first match for the given key => value pair and return the value
Array.prototype.assoc_search = function(what, array_key) {
let where = this;
for (var key in where) {
if (where[key].hasOwnProperty(array_key) && where[key][array_key] == what) {
return where[key][array_key];
}
}
return false;
};
}
var result = arrayC.assoc_search("omer", "name");
(result) ? console.log('found ' + result): console.log('not found ');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var person = {firstName:"John", lastName:"Doe", age:46};var persons = {{firstName:"John", lastName:"Doe", age:46}, {firstName:"Tom", lastName:"Dav", age:25}, ...}and find by firstName, for example