find a value inside array of JSON object

Let's create a function to get an object in an array for that, that takes two arguments: the array and the key of the property you want to get:

function getObjectInArray(arr, key) {    
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].hasOwnProperty(key)) return arr[i][key];
    }
}

This loops through each object looking for that specific key.


Solution: Now you could do something like getObjectInArray(titlesJSONArray, "Book2") and it should return "BULLETIN 2".

var titlesJSONArray = [ { "Book3": "BULLETIN 3" }, ... ]; // and so on
var book2 = getObjectInArray(titlesJSONArray, "Book2"); // => "BULLETIN 2"

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 */;

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

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.