I get below Array of JSON objects from JSP
"Titles":[
{
"Book3" : "BULLETIN 3"
}
,
{
"Book1" : "BULLETIN 1"
}
,
{
"Book2" : "BULLETIN 2"
}
]
On JS side, it is parsed and I see an array with 3 objects. Now, I want to find/identify a value when I pass String key.
For e.g. when I pass "Book2" I should get value "BULLETIN 2". Can someone help me identify the approach?
Try this
var data = {
"Titles": [{
"Book3": "BULLETIN 3"
}, {
"Book1": "BULLETIN 1"
}, {
"Book2": "BULLETIN 2"
}]
};
function getValueByKey(key, data) {
var i, len = data.length;
for (i = 0; i < len; i++) {
if (data[i] && data[i].hasOwnProperty(key)) {
return data[i][key];
}
}
return -1;
}
console.log(getValueByKey('Book2', data.Titles));
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 */;
To achieve this, you have to loop through the array elements's keys and test if the given key exists in the array, if so get its value:
var jsonTitles = [
{ "Book3" : "BULLETIN 3" },
{ "Book1" : "BULLETIN 1" },
{ "Book2" : "BULLETIN 2" }
]
function getValue(key, array) {
for (var el in array) {
if (array[el].hasOwnProperty(key)) {
return array[el][key];
}
}
}
alert(getValue("Book1", jsonTitles));
We use element[key]
where element is array[el]
to get the value of the given key
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With