javascript - Is it possible to check the condition of a value of an object and JUST return the key? -
i have object of letters , numbers inside of function. function takes in array of numbers , i'm running in loop iterates on object , checks condition. if of numbers in array match of values in object, return just key value.
so if pass in switcher(['26'])
, should return 'a'. possible?
function switcher(x){ const letters = { a: '26', b: '25', c: '24', d: '23', e: '22', f: '21', g: '20', h: '19', i: '18', j: '17', k: '16', l: '15', m: '14', n: '13', o: '12', p: '11', q: '10', r: '9', s: '8', t: '7', u: '6', v: '5', w: '4', x: '3', y: '2', z: '1' }; }
i have attempted via es6 map()
method, unsure put in if statement.. here have far:
return x.map(function(number){ let keys = object.keys(letters); for(var key in letters){ if(letters[key] === number){ } } }); }
is there easier way this?
you use object.keys
, array#find
key
of matched value
.
const letters = {a:'26',b:'25',c:'24',d:'23',e:'22',f:'21',g:'20',h:'19',i:'18',j:'17',k:'16',l:'15',m:'14',n:'13',o:'12',p:'11',q:'10',r:'9',s:'8',t:'7',u:'6',v:'5',w:'4',x:'3',y:'2',z:'1'}; function switcher(num){ var res = object.keys(letters).find(v => letters[v] == num); return res; } console.log(switcher('26')); console.log(switcher('9'));
Comments
Post a Comment