Thursday, 13 April 2017

JS creating/looping nested array with objects under a unique key

Still very new to JS and I would know how to do this with PHP but I can't seem to get it to work here. I'm working with Node here if that is relevant but I'm trying to achieve an array like this:

[ G: [ 'Gengerch, Melanie', 'Gomen, San' ],
  L: [ 'Lee, Ron', 'Loren, Tara' ],
  M: [ 'Mo, Sarah', 'Morrissey, Tag' ],
  T: [ 'Traeger, Stephen', 'Tran, Henry' ],
  Y: [ 'Young, Sam' ],
  Z: [ 'Zhao, Lily' ] 
]

This is how I have the loop:

var emp_list = [];
for(var i=0; i< employees.length; i++) {
    if(employees[i].firstletter == employees[i].last_name.charAt(0)) {
        var key = employees[i].firstletter;
        emp_list[key] = [employees[i].last_name + ', '+ employees[i].first_name];
    }
}

But of course with this I only get back the one name, and it is that last one from my db query.



via SVY

No comments:

Post a Comment