Raymon Schouwenaar

3 ways to loop over Object properties with Vanilla JavaScript

Written by Raymon on , time to read ~2 minutes.

It happens a lot that you need to loop over an Array with JavaScript Objects! But sometimes you just don’t know what kind of properties that Object has. Lucky we are that JavaScript offers a few ways of looping over JavaScript Object properties.

I wanted to share 3 of them with you. So hopefully this will help you in the right direction.

The Object to loop over

First, we need an example object to loop over. So I put some of my experience in it 😉 (hahaha)! Keep the fun in it!

    
        
let experienceObject = {
    name: 'Raymon',
    title: 'Lead Frontend/JavaScript Developer',
    yearsExperience: 8,
    projects: [
        {
            name: 'ANWB',
            title: 'Senior JavaScript Developer',
            techniques: ['Angular', 'ES6', 'Vanilla JavaScript', 'Less', 'CSS']
        },
        {
            name: 'NATO',
            title: 'Lead JavaScript Developer',
            techniques: ['Angular 2', 'AngularJS', 'ES6', 'Vanilla JavaScript', 'Web Sockets', 'D3']
        },
        {
            name: 'Rabobank',
            title: 'Senior Frontend Developer',
            techniques: ['Vanilla JavaScript', 'CSS', 'Responsive Webdesign']
        }
    ]
}

    

Object.keys(experienceObject).map()

The first example is the Object.keys map method to loop over the properties of the Object it.

    
        
Object.keys(experienceObject).map(e => {
    console.log(`key= ${e} value = ${experienceObject[e]}`)
});

    

Object.entries(experienceObject).forEach()

The second example is the Object.keys with the forEach method over the properties of the Object it.

    
        
Object.entries(experienceObject).forEach(([key, value]) => {
    console.log(`key= ${key} value = ${value}`)
})

    

For-in loop

The last example is the For-in loop to loop over the properties of the Object it.

    
        
for (property in experienceObject) {
  console.log(`key= ${property} value = ${experienceObject[property]}`)
}

    
comments powered by Disqus

Readmore

CSS Grid Layout Metro design blocks

The times have come that we don’t have to fiddle around with Floats and Tables anymore! Flexbox is already an established term in the industry of Frontend Developers.

3 ways to loop over Object properties with Vanilla JavaScript

It happens a lot that you need to loop over an Array with JavaScript Objects! But sometimes you just don’t know what kind of properties that Object has. Lucky we are that JavaScript offers a few ways of looping over JavaScript Object properties.