user3787706
user3787706

Reputation: 659

Length of empty array in javascript

so i'm trying to do one of the most basic things, and i am wondering what's wrong with my approach.

i have an object containing rooms

{ rooms: 
   { ijxeczyu: 
      { Id: 'ijxeczyu',
        teacherName: 'testteacher',
        teacherId: '/#Ikosyfr1NtDcpKbaAAAA',
        clients: [] } },
  getRooms: [Function],
  addRoom: [Function] }

now i want to render their info to a table in jade. for that to work, i want to extract the important stuff and push it to an array

function makeArray(obj) {

  var roomArray = [];

  for (var room in obj) {
    roomArray.push({
      roomId  : room.Id,
      teacher : room.teacherName,
      clients : room.clients.length || 0
    })
  }
  return roomArray;
}

pretty easy. but i can't get that empty clients array to work. TypeError: Cannot read property 'length' of undefined isn't that exactly what the || 0part should catch?

why doesn't this work? how can i read the length of an array or 0 if there are no entries?

Upvotes: 0

Views: 1518

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32521

room.clients is undefined which is why you get that error. The reason it's undefined is because room is a string.

A for..in loop iterates over the keys of an object. This means that room === "ijxeczyu", assuming you're passing in your rooms object. To get access to the object, you'll have to access the object at that key.

for (var name in obj) {
  var room = obj[name];
  ...
}

Upvotes: 4

Related Questions