0

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
4
  • 1
    What have you tried? Commented Jul 3, 2012 at 19:58
  • @Merlin means "don't post code in comments, edit your question" Commented Jul 3, 2012 at 20:03
  • @Moushigo So, you've tried that, and what was the problem with it? What output were you getting and why was it wrong? Commented Jul 3, 2012 at 20:04
  • @Merlin sorry about that. First time. Commented Jul 3, 2012 at 20:10

1 Answer 1

2

The property val.highlight does not exist, which is why you're getting undefined. Your object has an array value for the key of #text. The highlight key is a separate property and thus cannot be accessed in the current context.

The solution below corrects the refence to allow the highlight value to be referenced. I've added additional indicators for illustrative purposes.

JavaScript:

var obj = {
    "context": {
        "#text": [
            "Most Visited Pages  ",
            " Hall Residents Advanced Components",
            " Clerk"
        ],
        "highlight": [
            "City",
            "City"
        ]
    }
};

var result = [];
var data = obj.context;

for(var i=0; i < data['#text'].length; i++){
    result[i] = data['#text'][i] + (data.highlight[i] ? '<highlight>' + data.highlight[i] + '</highlight>' : '');
}

document.getElementById('result').innerHTML = result.join('');

alert(document.getElementById('result').innerHTML);

Demo: http://jsfiddle.net/Wv3vH/

NOTE: the above data attempts to compare two arrays of equal length. Since the #text array is one larger than the highlight array, there is an undefined value which is not displayed due to the boolean logic to check if the value exists.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.