Seems Just like the letter -y at the end of a or Spanish (or English?) word is a glorified i, to make it more legible // Ley, rey, etc.
As the other user correctly highlighted, Spanish didn't inherit Latin's nominative forms (lex, rex, nox...); it inherited the accusative ones (legem→ley, regem→rey, noctem→noche).
The pronunciation of those words changed. And alongside it, the spelling. That Latin ⟨g⟩ in legem, regem used to be pronounced [g], like in English "gift" or "good"; but eventually it was softened to a [j], as in English "yes". And the ending of the word was lost.
This wasn't just Spanish, mind you, but pretty much all Western Romance languages. (Italian sometimes dropped it - cue to re, but legge). Then how you write that /j/ down is up to spelling conventions: Spanish picked ⟨y⟩, Galician ⟨i⟩ (rei, lei), and French went back and forth (in MF the spelling was still "roy, loy", but nowadays "roi, loi").
Edit: on the other hand, x used to be read /j/ (e.g. Quixote, Mexico), so also possibly lex —> lej —> ley
Spanish ⟨x⟩ used to be read /ʃ/, as in modern French and Portuguese. (It's the first sound of "shampoo"). While ⟨j⟩ was used for the voiced counterpart, /ʒ/ (as in "Asia") or /dʒ/ (as in "jeans"). Eventually both merged, got backed to the modern /x/ (as Scottish "loch"), and the resulting merge is now spelled with ⟨j⟩.
Addressing HN comments:
As the other user correctly highlighted, Spanish didn't inherit Latin's nominative forms (lex, rex, nox...); it inherited the accusative ones (legem→ley, regem→rey, noctem→noche).
The pronunciation of those words changed. And alongside it, the spelling. That Latin ⟨g⟩ in legem, regem used to be pronounced [g], like in English "gift" or "good"; but eventually it was softened to a [j], as in English "yes". And the ending of the word was lost.
This wasn't just Spanish, mind you, but pretty much all Western Romance languages. (Italian sometimes dropped it - cue to re, but legge). Then how you write that /j/ down is up to spelling conventions: Spanish picked ⟨y⟩, Galician ⟨i⟩ (rei, lei), and French went back and forth (in MF the spelling was still "roy, loy", but nowadays "roi, loi").
Spanish ⟨x⟩ used to be read /ʃ/, as in modern French and Portuguese. (It's the first sound of "shampoo"). While ⟨j⟩ was used for the voiced counterpart, /ʒ/ (as in "Asia") or /dʒ/ (as in "jeans"). Eventually both merged, got backed to the modern /x/ (as Scottish "loch"), and the resulting merge is now spelled with ⟨j⟩.