Dynamically construct embedded data field name with loop and merge index | XM Community
Skip to main content
Is it possible to access an embedded data field in Javascript when dynamically constructing its field name?



For example, let's say the field I want is `result.elements.0.embeddedData.V1`, but I only know the last character should be `1` at runtime (the number is drawn from a loop & merge index).



I want to do something like:



var n = "${lm://CurrentLoopNumber}"; // ex. n = 1

var ed = eval("${e://Field/result.elements.0.embeddedData.V"+n.toString()+"}");



But this doesn't work, `ed` just comes up `null`.

(Sanity check: `console.log("${e://Field/result.elements.0.embeddedData.V1}");` does produce the value I'm expecting.)



I imagine this is because of the order of operations somehow (either that or `eval()` can't execute `$` syntax?) It seems like by the time my string concatenation occurs, there isn't a good way to access the embedded data with the concatenated name.



Any ideas?



Note: I found this answer which sets embedded data fields with the target index as a second L/M field.



E.g.



LM Field 1 = 2

LM Field 2 = ${e://Field/myfield_2}



That's close to what I want, but because my starting index is variable and is set by a query string, I need to do something more like



with start_ix = 1:

LM Field 1 = $e{e://Field/start_ix + 1}

LM Field 2 = $e{e://Field/myfield + $e{e://Field/start_ix + 1}}



But that doesn't work - nor do I expect it to, as I don't think embedded data "math" supports string concatenation in the same way the `+` operator can concat strings in Javascript.
Embedded variables are resolved on the survey before the page is sent to the browser. So, you can't dynamically create the name in JavaScript. Math operations, like in your last example, are also done on the server.



If the number is draw from the loop & merge, then put your embedded variables in the loop and merge setup and access them as loop & merge fields, such as ${lm://Field/2} if your embedded data is in the second field.

Leave a Reply