tengo un objeto
{ key: "#% chance to gain Unholy Might for # seconds on Kill", value: [ [10, 15], [3, 3] ] }Necesito reemplazar la tecla "#" en orden:
la tecla final debe verse (10-15)% chance to gain Unholy Might for 3 seconds on Kill
Debe iterar sobre los valores usando Array.prototype.reduce() . Luego, para cada valor, actualice el texto usando String.prototype.replace() :
const data = { key: "#% chance to gain Unholy Might for # seconds on Kill", value: [ [10, 15], [3, 3] ] }; const replateBy = (text, token, values) => { return values.reduce((text, [a,b])=> text.replace(token, `${a===b ? a: `(${a}-${b})`}`), text); } console.log(replateBy(data.key, "#", data.value));La forma más sencilla de hacer esto es con un replace . Dado que el primer # va seguido de un signo de porcentaje, podemos simplemente reemplazar #% para comenzar, lo que nos deja solo con el último # para reemplazar.
const data = { key: "#% chance to gain Unholy Might for # seconds on Kill", value: [ [10, 15], [3, 3] ] } // First we replace the #% with the actual percentage const stringWithPercentage = data.key.replace('#%', `(${data.value[0][0]}-${data.value[0][1]})%`) // Then we can use that value and replace the last # with the seconds const stringWithSeconds = stringWithPercentage.replace('#', data.value[1][0]) console.log(stringWithSeconds)Hay varias formas de lograr esto según sus necesidades y su voluntad de cambiar la estructura de datos.