Find key for object based on two properties

Viewed 24

Right now I can find the object key for a list of note by searching for its frequency:

let key = noteKeys.find(k=>note[k]['freq']===freq);

Each note has it's own unique frequency, so that's note a problem.

But say if I want to find the object key in my note object based on both the note letter value (a number) and an octave?

I'd imagine it would be something like this, but it gives me the error "malformed parameter list':

let key = noteKeys.find(k=>note[k]['note']===newNote && k=>note[k]['octave']===currentOctave)
2 Answers

=> is the part which separates the parameters from the function body of arrow functions.

Inside of an expression it throws an error, because of the wrong parameter list.

let key = noteKeys.find(k =>
        note[k]['note'] === newNote && note[k]['octave'] === currentOctave
    );

A bit shorter

let key = noteKeys.find(k => 
        note[k].note === newNote && note[k].octave === currentOctave
    );

Everything after => is the function body, and in this case (due to lack of curly braces denoting a block) also the return expression of the function.

By doing && k=> ... you are creating a new anonymous function, whose truthy-ness in a boolean expression will always be true.

Remove the second k => and you'll have a boolean expression that asserts both note[k]['note']===newNote AND note[k]['octave']===currentOctave:

let key = noteKeys.find(k=>note[k]['note']===newNote && note[k]['octave']===currentOctave)

Or, alternatively and perhaps more easily understandable:

let key = noteKeys.find(k=> {
  return note[k]['note'] === newNote && note[k]['octave'] === currentOctave)
})

As a follow up, you should read about arrow functions and boolean expressions.

Related