Joti Basi Joti Basi - 1 year ago 87
Javascript Question

Angular.js / Javascript: checking if an object is found in any of the elements of an array

I have an array that is structured like this:

$scope.roomlist = [
{"roomid":"1", "tablecount":"10", "chaircount":"20", "whiteboards":"2"},
{"roomid":"2", "tablecount":"15", "chaircount":"30", "whiteboards":"2"},
{"roomid":"3", "tablecount":"10", "chaircount":"20"}];

The array values are dynamic and the array is generated by joining some tables. Whiteboards is one of the elements that may exist in all the rooms returned in the
, may exist in some of the rooms as shown above or none of the rooms at all.

All I need to do is test to see if there is at least one room in the list which has the whiteboard object.

I have tried the
test but it returns -1.

The code I executed, was

var myrooms = $scope.roomlist;
var results = myrooms.indexOf("whiteboards");

And then


Any suggestions?

Answer Source

You need to iterated room by room, and then check for existence.

function searchRoomsFor(objectName, roomList) {
  var found = false;
  for (var roomIndex in roomList) {
    var room = roomList[roomIndex];
    if (objectName in room) {
      found = true;
  return found;

// Check for an object
console.log(searchRoomsFor('whiteboards', $scope.roomlist));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download