Reputation: 171
I have this array with several id's and heights.
How can i get a hight of a specific id given?
like get the value of review-1 from the array? which is "500px"?
thanks.
ar=[];
ar.push({"id":"reiew-1","height":"500px"});
$.each(ar,function(index,value){
alert(value.height); // gets all the heights
});
Upvotes: 0
Views: 73
Reputation: 5676
You could go functional
and do something like this:
ar=[
{"id":"reiew-1","height":"500px"},
{"id":"reiew-2","height":"600px"},
{"id":"reiew-3","height":"700px"},
];
filterById=function(value){
return function(o){
return o["id"]===value;
};
}
getAttribute=function(value){
return function(o){
return o[value];
}
}
ar.filter(filterById("reiew-1")).map(getAttribute("height"))
Which is easy on the eyes :]
Here is the fiddle
For more information (e.g. about browser compatibility), here are the MDN links:Array.prototype.filter()
and Array.prototype.map()
Upvotes: 0
Reputation: 3665
So you can use only javascript methods to do this things
var ar=[];
ar.push({"id":"reiew-1","height":"500px"}, {"id":"reiew-3","height":"500px"});
// function that filter and return object with selected id
function getById(array, id){
return array.filter(function(item){
return item.id == id;
})[0].height || null;
}
// now you can use this method
console.log(getById(ar, "reiew-1"))
You can play with this code, demo
Upvotes: 1
Reputation: 388436
Use an if condition within the loop
ar = [];
ar.push({
"id": "reiew-1",
"height": "500px"
});
$.each(ar, function (index, value) {
if (value.id == 'reiew-1') {
alert(value.height); // gets all the heights
return false;//stop further looping of the array since the value you are looking for is found
}
});
Upvotes: 1