DEV Community

Cover image for forEach( ): Object.values / Object.keys
Luca
Luca

Posted on

forEach( ): Object.values / Object.keys

Hi!🙋‍♂️

I wrote this article for show you this 3 forEach ways:

Take this simply array:

var array = [
    {
        name: 'John'
    },
    {
        name: 'Mary'
    }
];
Enter fullscreen mode Exit fullscreen mode

If you want to cycle the element with forEach() method, you have three ways:

Keys:

Object.keys

Object.keys(array).forEach(function(key) {
    console.log(key); //--> 0 1
});
Enter fullscreen mode Exit fullscreen mode

Values:

Object.values

Object.values(array).forEach(function(value) {
    console.log(value);  //--> name: 'John' name: 'Mary'
    console.log(value.name);  //--> John Mary
});
Enter fullscreen mode Exit fullscreen mode

forEach:

.forEach

array.forEach(function (val) {
    console.log(val); //--> name: 'John' name: 'Mary'
})
Enter fullscreen mode Exit fullscreen mode

Discussion (0)