How do I transform this JSON object:
"context":{"#text":["Most Visited Pages ","
Hall Residents Advanced Components"," Clerk"],"highlight":["City","City"]}
into:
Most Visited Pages <highlight>City</highlight>
Hall Residents Advanced Components <highlight>City</highlight> Clerk
by using Javascript?
I have tried:
function highlightContext_22(context) {
var highlighted;
$.each(context['#text'], function(key, val) {
highlighted += val + val.highlight;
});
return highlighted;
}
Output is:
undefinedMost Visited Pages undefined
Hall Residents Advanced Components undefined Clerkundefined
The property
val.highlightdoes not exist, which is why you’re getting undefined. Your object has an array value for the key of#text. Thehighlightkey is a separate property and thus cannot be accessed in the current context.The solution below corrects the refence to allow the
highlightvalue to be referenced. I’ve added additional indicators for illustrative purposes.JavaScript:
Demo: http://jsfiddle.net/Wv3vH/
NOTE: the above data attempts to compare two arrays of equal length. Since the
#textarray is one larger than thehighlightarray, there is an undefined value which is not displayed due to the boolean logic to check if the value exists.