I have the following information:
The city name, in this case Littelside. This is stored in a variable
var city
I have an array of {} objects. Each contains address, city, name, state and zip-code
[{"address":"07288 Albertha Station",**"city":"Littelside"**,"created_at":"2011-05-25T19:24:51Z","id":1,"name":"Mr. Emmitt Emmerich","state"开发者_开发问答:"Missouri","updated_at":"2011-05-25T19:24:51Z","zip":"75475-9938"},{NEXT OBJECT WITH ADDRESS CITY ETC}]
How do you use the var city
as a search term to parse the array, and return address, city, state, name and zip of the array with the matching city?
Thanks!
The function you're looking for is $.grep()
.
var city='Littelside';
var cucc=$.grep(your_array, function (a) {
return a.city==search;
})[0];
$.grep
will still return an array, with all the elements inside that satisify the filter function. Here I've use [0]
to get the first result, which is fine in case you're sure that there will be one result. So cucc
will have the whole object you're looking for.
jsFiddle Demo
var myarr = [{"address":"07288 Albertha Station","city":"Littelside","created_at":"2011-05-25T19:24:51Z","id":1,"name":"Mr. Emmitt Emmerich","state":"Missouri","updated_at":"2011-05-25T19:24:51Z","zip":"75475-9938"}];
var city = 'Littelside';
$.each(myarr,function(key,value){
if(value['city']== city){
alert('hello');
}
})
here's a working demo
A function I use.
function arrayIndexOfProp(arr, prop, obj) {
var i = arr.length;
while (i--) {
if (arr[i] && arr[i][prop] === obj) {
return i;
}
}
return -1;
}
var index = arrayIndexOfProp(theArray, "city","Littelside");
// do stuff with theArray[index]
Array.prototype.reduce as in
Array.prototype.reduce(
function (prev, current) {
return prev || current.city === "Littelside" ? current : null;
})
Loop over the array until you find one where the_array[i].city
matches.
精彩评论