Estoy trabajando con un elemento svg y estoy tratando de crear un elemento de text recuperando dinámicamente un parámetro que se pasa a un argumento de función anterior.
Por ejemplo, una muestra mínima
const data = [{ "Month": 1, "Value": 10000, "MonthName": "Jan" }, { "Month": 2, "Value": 20000, "MonthName": "Feb" }]; const data2 = data.map((x)=>x.Value); // targeting the svg itself const svg = document.querySelector("svg"); // variable for the namespace const svgns = "http://www.w3.org/2000/svg" const text1 = document.createElementNS(svgns, "text") text1.setAttribute('x', '10'); text1.setAttribute('y', '10'); text1.textContent = 'Value'; svg.appendChild(text1); <svg class="layer1" xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200"> </svg> En este caso, ¿hay alguna forma de que javascript devuelva la declaración const data2 como una cadena para poder generar dinámicamente el contenido de texto como se muestra a continuación?
const data = [{ "Month": 1, "Value": 10000, "MonthName": "Jan" }, { "Month": 2, "Value": 20000, "MonthName": "Feb" }]; const data2 = data.map((x)=>x.Value); // targeting the svg itself const svg = document.querySelector("svg"); // variable for the namespace const svgns = "http://www.w3.org/2000/svg" const text1 = document.createElementNS(svgns, "text") text1.setAttribute('x', '10'); text1.setAttribute('y', '10'); text1.textContent = `data.map((x)=>x.Value)`.match(/(?<=x\.)[a-zA-Z]+/gm); svg.appendChild(text1); <svg class="layer1" xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200"> </svg>Entonces, en lugar de codificar,
text1.textContent = 'Value';Deseo escribir lo siguiente ya que const data2 variará. Por ejemplo, puede ser x.Mes/x.NombreMes
text1.textContent = {a function that returns const data2 expression as string}`data.map((x)=>x.Value)`.match(/(?<=x\.)[a-zA-Z]+/gm);No, no hay forma de obtener la expresión que se usó en la declaración de una variable como una cadena.
Deberías resolver esto con un nivel de indirección. Coloque la propiedad en una variable de cadena y úsela cuando calcule data2 y también para textContent .
const data2_prop = 'Value'; const data2 = data.map((x) => x[data2_prop]); ... text1.textContent = data2_prop;