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?

3
  • See stackoverflow.com/questions/14379274/javascript-iterate-object. Commented Aug 18, 2016 at 4:09
  • @torazaburo This is not a duplicate. I know the for-loop method, but I want to use forEach, which I thought I could. Commented Aug 18, 2016 at 4: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. Commented Aug 18, 2016 at 5:22

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You are correct. Somehow I got the misconception that I should able to use it that way and has been bugging me for awhile.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.