Having:
var x = [{
"Book3" : "BULLETIN 3"
}, {
"Book1" : "BULLETIN 1"
}, {
"Book2" : "BULLETIN 2"
}];
and
var key = "Book1";
You can get the value using:
x.filter(function(value) {
return value.hasOwnProperty(key); // Get only elements, which have such a key
}).shift()[key]; // Get actual value of first element with such a key
Notice that it'll throw an exception, if object doesn't have such a key defined.
Also, if there are more objects with such key, this returns the first one only. If you need to get all values from objects with such key, you can do:
x.filter(function(value) {
return value.hasOwnProperty(key); // Get only elements, which have such a key
}).map(function(value) {
return value[key]; // Extract the values only
});
This will give you an array containing the appropriate values only.
Additionally, if you're using jQuery
, you can use grep
instead of filter
:
jQuery.grep(x, function(value) {
return value.hasOwnProperty(key);
}) /* and so on */;