Find a Particular item within an Array of Objects

When we use array objects in JavaScript or JQuery, it often required us to find a particular item of the array depending upon a particular field value.  We can easily find this.
 
For doing this, we first we have to create an array objects like below:
  1. var source = [{  
  2.     Id: 1,  
  3.     City: "Kolkata",  
  4.     State: "West Bengal",  
  5.     Region: "East"  
  6. }, {  
  7.     Id: 2,  
  8.     City: "New Delhi",  
  9.     State: "Delhi",  
  10.     Region: "North"  
  11. }, {  
  12.     Id: 3,  
  13.     City: "Mumbai",  
  14.     State: "Maharastra",  
  15.     Region: "West"  
  16. }, {  
  17.     Id: 4,  
  18.     City: "Chennai",  
  19.     State: "Tamilnadu",  
  20.     Region: "South"  
  21. }, {  
  22.     Id: 5,  
  23.     City: "Bangalore",  
  24.     State: "Karnataka",  
  25.     Region: "South"  
  26. }];  
Now suppose we want to find the particular item within the array based on City name. Like if we provide city name as Chennai, then it will return the entire details of chennai .
 
For this, we right down the below code:
  1. var result_obj = objectFindByKey(source, 'City''Chennai');  
  2.   
  3. function objectFindByKey(array, key, args)   
  4. {  
  5.     for (var i = 0; i < array.length; i++)   
  6.     {  
  7.         var value = array[i][key];  
  8.         var type = typeof value;  
  9.         if (type == "number") {  
  10.             if (array[i][key] === Number(args))   
  11.             {  
  12.                 return array[i];  
  13.             }  
  14.         } else {  
  15.             if (array[i][key] === args)   
  16.             {  
  17.                 return array[i];  
  18.             }  
  19.         }  
  20.     }  
  21.     return null;  
  22. }  
Ebook Download
View all
Learn
View all