EN
JavaScript - why is forEach not a function for this object?
1 answers
0 points
JavaScript keeps throwing me this error:
xxxxxxxxxx
1
TypeError: values.forEach is not a function
When I try to do something like:
xxxxxxxxxx
1
var values = {
2
a: 'value A',
3
b: 'value B',
4
};
5
6
values.forEach(function(key, value) {
7
console.log(value);
8
});
Why is that so?
1 answer
0 points
Objects don't have forEach()
method, it can be only used with arrays.
However, since ES8 (ECMAScript 2017) there is Object.values()
method that returns array of the object's values. You can use it to create array of values and then iterate it with forEach()
.
Practical example
xxxxxxxxxx
1
var myObject = {
2
a: 'value A',
3
b: 'value B',
4
};
5
6
Object.values(myObject).forEach(function(value) {
7
console.log(value);
8
});
Alternative solution
As an alternative for older versions of JavaScript, you can use Object.keys()
method that returns array of the object's keys and then use array notation to get values.
xxxxxxxxxx
1
var values = {
2
a: 'value A',
3
b: 'value B',
4
};
5
6
Object.keys(values).forEach(function(key) {
7
console.log(values[key]);
8
});
References
0 commentsShow commentsAdd comment