Search code examples
javascriptoopecmascript-5

Iterating through a JavaScript Object


Having trouble accessing objects. They are printing as undefined. Help! I need the code to print the student names.

let students = [
        {name: 'Remy', cohort: 'Jan'},
        {name: 'Genevieve', cohort: 'March'},
        {name: 'Chuck', cohort: 'Jan'},
        {name: 'Osmund', cohort: 'June'},
        {name: 'Nikki', cohort: 'June'},
        {name: 'Boris', cohort: 'June'}
    ];



    function objPrint() {
        for (var i=0; i<students.length; i++) {
           console.log("Name: " + students[i][0] + " Cohort: " + students[i][1])
        }
    }

Solution

  • Do something like this:

    let students = [
        {name: 'Remy', cohort: 'Jan'},
        {name: 'Genevieve', cohort: 'March'},
        {name: 'Chuck', cohort: 'Jan'},
        {name: 'Osmund', cohort: 'June'},
        {name: 'Nikki', cohort: 'June'},
        {name: 'Boris', cohort: 'June'}
    ];
    
    
    
    function objPrint() {
        for (var i=0; i<students.length; i++) {
           // Can also use students[i]['name'] , students[i]['cohort']
           // using lodash.js _.get(students, [i, 'name'], 'default value');
           // using new destructuring let {name, cohort} = students[i] then console.log("name: "+ name + " Cohort: "+cohort);
           console.log("Name: " + students[i].name + " Cohort: " + students[i].cohort);
        }
    }