0

I need find a value in associative array by it key. Is it possible to do something like this?

$.fn.array_search = function(what, where, array_key){

    for (var key in where) {
        if (where[key].array_key == what) return true;
    }
    return false;
}
3
  • when you say associative array you mean some thing like var person = {firstName:"John", lastName:"Doe", age:46}; Commented Dec 5, 2017 at 21:13
  • @MuhammadOmerAslam, like var persons = {{firstName:"John", lastName:"Doe", age:46}, {firstName:"Tom", lastName:"Dav", age:25}, ...} and find by firstName, for example Commented Dec 5, 2017 at 21:17
  • just added an answer for you Commented Dec 5, 2017 at 22:01

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.