A. R. A. R. - 5 months ago 13
JSON Question

find a value inside array of JSON object

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?

Answer

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