How do I change one of the enchantment levels of an item to a scoreboard value

Solution 1:

You can use /data modify and /execute store to make this happen.

If you are using a scoreboard number to represent your enchantment ID, translating it into the NBT string for the enchantment ID will have to be hard-coded. Sorry, there's no way around that.

But for the enchantment level, let's get the magic commands started.

Let's say your item is in a chest at coordinates (12, 23, 34), in slot 0 (the upper left one). You can add an enchantment like so:

/data modify block 12 23 34 Items[{Slot:0b}].tag merge value {Enchantments:[{id:"minecraft:sharpness",lvl:1s}]}

This command should add a single enchantment to the item. The values are for now temporary, but we're about to modify them:

/execute if score @p enchantmentID matches 1 run data modify block 12 23 34 Items[{Slot:0b}].tag.Enchantments[0] merge value {id:"minecraft:smite"}

If ID 1 corresponds to Smite in your map, run this command. Change the values as you wish.

/execute store result block 12 23 34 Items[{Slot:0b}].tag.Enchantments[0].lvl short 1.0 run scoreboard players get @p enchantmentLvl

This means, get the nearest player's score for enchantmentLvl, and store it as a short int in the item's first enchantment.

Remember, neither command can modify player NBT, In layman's terms, you can't modify items still in the inventory. You'll have to get the players to place their item in a chest or other container. For most reliability, have them drop it into a hopper funneling into a chest. This means the item will always end up in slot 0, ensuring you clear the chest after each use.