Joti Basi Joti Basi - 1 year ago 103
AngularJS Question

Angular.js / Javascript: checking if an object if 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 generating by joining some tables. Whiteboards is one of the elements that may exist in all the rooms returned in the roomlist, 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 indexOf 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