2

In the following JavaScript code,

obj = {};

// This work as intented
obj['a'] = { item1: 'a1', item2: 'a2' };
console.log(obj);

// Object.keys() works too
console.log(Object.keys(obj));

// forEach does not, why? and how to fix?
console.log('forEach');
obj.forEach(o => console.log(o));

What is needed to have forEach working?

John Siu
  • 5,056
  • 2
  • 26
  • 47
  • See http://stackoverflow.com/questions/14379274/javascript-iterate-object. –  Aug 18 '16 at 04:09
  • @torazaburo This is not a duplicate. I know the for-loop method, but I want to use forEach, which I thought I could. – John Siu Aug 18 '16 at 04:47
  • You can't, because `forEach` does not exist on objects. The duplicate question goes into great detail on how to loop across object properties, including `forEach` across object keys, `for...in`, and newer ES6 approaches. –  Aug 18 '16 at 05:22

1 Answers1

4

What you have here is a JavaScript question, not a TypeScript question. TS and JS have the same runtime semantics.

forEach is a method of Array. Objects don't have forEach. The semantics of forEach don't make sense on regular objects -- your obj doesn't have a length or a 0 property, for example, which are the kinds of things forEach looks for.

Ryan Cavanaugh
  • 209,514
  • 56
  • 272
  • 235
  • You are correct. Somehow I got the misconception that I should able to use it that way and has been bugging me for awhile. – John Siu Aug 18 '16 at 03:23