thanks_in_advance
thanks_in_advance

Reputation: 2743

getting key, value of 'this': what would be equivalent jQuery for javascript?

Is it possible to re-write the following using $(this) instead of this (without needing any additional information)? If yes, then what would it look like?

 $.each(this, function(key,value){
    alert(key + " " + value);
 })

Background: this is what the overall program looks like:

var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };

$.each(data.programs, function(i){

     $.each(this, function(key,value){
        alert(key + " " + value);
     })
})

Upvotes: 2

Views: 57

Answers (1)

YaBCK
YaBCK

Reputation: 3029

You can just store the $(this) into a variable and use the variable in the $.each and it'll work the same as your first $.each or you could use a simple for loop instead of using a second '$.each'.

Two examples of how you could do this:

var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };

$.each(data.programs, function(i)
{
     var dataPrograms = $(this);
     $.each(dataPrograms[0], function(key, value)
     {
       console.log("JQUERY: [KEY]" + key + " " + "[VALUE]" + value);
     })
});

$.each(data.programs, function(i)
{
     var dataPrograms = $(this);
  
     for (i = 0; i < dataPrograms.length; i++) 
     { 
       console.log("NAME: " + dataPrograms[i].name);
       console.log("PRICE: " + dataPrograms[i].price);
     }
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Upvotes: 2

Related Questions