1

I'm trying to get my head around arrays in jQuery. Let's take the following scenario. I have an array of data, like so:

var myVariable = [
    'key1' : 'value1',
    'key2' : 'value2',
    'key3' : 'value3',
    'key4' : 'value4'
] 

And here is a list of elements:

<ul id="elem">
    <li class="key1">Item 1</li>
    <li class="key2">Item 2</li>
    <li class="key3">Item 3</li>
    <li class="key4">Item 4</li>
</ul>

How would I go about creating an if statement to run through each element, if the class is identified in the array then replace the text content? So the final output should be:

<ul id="elem">
    <li class="key1">key1</li>
    <li class="key2">key2</li>
    <li class="key3">key3</li>
    <li class="key4">key4</li>
</ul>

I have tried with the following but it doesn't appear to work.

$('#elm li').each(function (index) {
    $(this).text(myVariable[index]);
});

I realise there aren't associative arrays in JS but I'm not really understanding how it work.

Please point me in the right direct. Thanks!!

1
  • 3
    Your variable is a syntax error. The contents look like object properties, but you've used [ ] which are for creating arrays. Commented Jul 22, 2013 at 15:02

3 Answers 3

3

One way:

$("#elem li").text(function(i, text) {
    return this.className in myVariable
         ? myVariable[this.className] : text;
});

Another way:

$.each(myVariable, function(key, value) {
    $("#elem li." + key).text(value);
});

N.B.: In JavaScript arrays with non numeric keys are objects and should be surrounded with {}, but not with [], as in plain arrays.

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

2 Comments

Thanks! I used the second option as I find it easier to read. Is there any real difference between the two approaches that I should be aware of?
@Sheixt Yes, the first one is much faster :)
2

Try this...

var myVariable = {
    'key1' : 'value1',
    'key2' : 'value2',
    'key3' : 'value3',
    'key4' : 'value4'
};
$("#elem li").text(function() {
    return myVariable[this.className] == '' ? this.text(): myVariable[this.className];
});

Working fiddle here PS: I know it is similar to the first answer, but i have seen it after posted this one:(

1 Comment

Callback function in .text() already have current value in its arguments.
0
$( '#elm li').each( function() {  
    var text = myVariable[ $( this ).className ] ? myVariable[ $( this ).className ] : '';   
    $( this ).text( text );   
});

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.