HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Replacing text in an array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraytextreplacing

Problem

I have this piece of code to replace current text inside an array of html divs with values coming from a JSON file:

$.each($('.something'), function(){
        if($(this).text()=="1"){
            $(this).html(jsondata.CameraTypeLabel1);
        }else if($(this).text()=="2"){
            $(this).html(jsondata.CameraTypeLabel2);
        }
    });


I'd like to make it "dynamic": if I'd have 100 values, I don't want to copy/paste it 100 times.

Maybe it would be better creating an array "CameraTypeLabel" in the JSON string ?

EDIT: Fixed the selector, it was a typo.

Thanks!

Solution

jQuery's .html() method can take a callback function - it'll be called for every element in the collection - and will use the returned value to set the element's html.

You can use bracket notation to access the key in your jsondata, so that you can dynamically get to the key you want with the string in the brackets:

$('.something').html(function () {
    return jsondata[ 'CameraTypeLabel' + $.text(this) ];
});


Note: $.text(this) is the same as $(this).text(), just a bit faster; it doesn't create a new jQuery object at every step in the loop.

If all you want to do is update the text, you can pass a function to .text() itself:

$('.something').text(function (i, oldText) {
    return jsondata[ 'CameraTypeLabel' + oldText ];
});

Code Snippets

$('.something').html(function () {
    return jsondata[ 'CameraTypeLabel' + $.text(this) ];
});
$('.something').text(function (i, oldText) {
    return jsondata[ 'CameraTypeLabel' + oldText ];
});

Context

StackExchange Code Review Q#21440, answer score: 3

Revisions (0)

No revisions yet.