Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  116] [ 2]  / answers: 1 / hits: 65423  / 9 Years ago, wed, april 29, 2015, 12:00:00

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?


More From » json

 Answers
13

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));




[#66834] Tuesday, April 28, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nestorjarettg

Total Points: 451
Total Questions: 108
Total Answers: 108

Location: Rwanda
Member since Thu, Feb 10, 2022
2 Years ago
;