John Siu John Siu - 3 months ago 19
Javascript Question

Javascript object forEach howto?

This has puzzle me for awhile and I am not be able to find an answer to it.

In 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?

Thank you!

(It keep asking me to put in more details .....................................................................................)

Answer

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.

Comments