I am looping through my array to get the corresponding field value:
var someFun = function (nm) {
var names = [{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}];
for (var i=0; i < names.length; i++) {
if (names[i].name === nm) return names[i].age;
}
};
var username = 'tom';
var printme = someFun(username);
console.log('hey: ', printme)
How can I do the same using Object.keys(), or map, or forEach? Much cleaner and ES6 compliant.
namesis an array. You would not useObject.keys!return {joe: 'nine', tom: 'ten'}[nm];would do the job :-)for(var key in names[i]){ console.log("key: " + key + ", value: " + names[i][key]); }