0

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?

1
  • 2
    Presuming you mean that room.clients is undefined, then the || 0 is too late. Instead, you can do: (room.clients || []).length Commented Jan 27, 2016 at 22:39

1 Answer 1

4

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];
  ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

aaaaahhhh ok. now it makes sense. so basically, a for..in loop is pretty much no advantage over a standard for loop?
@user3787706 The advantage is that you can use it to iterate over the keys of an object. A standard for loop is for iterating over arrays. for (var key in obj) vs. for (var i = 0; i < array.length; i++). You could also get the keys using Object.keys(obj) then use a standard for loop over those.
Ecmascript 7 adds for value of object, which iterates over the values instead of the keys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.