Friday, February 7, 2014

Iterate (Loop) Object (Key value pair) in JavaScript and JQuery

Let assume y is our object which has following data and you need to iterate it in native JavaScript

var y = {1: "2", name: "value", sN: "sV"}
$.each(y,function(k,v){alert(k + v)});

in jQuery you can do the same thing like below

var Y = {1: "2", name: "value", sN: "sV"}
for (var k in Y) {
        if (y.hasOwnProperty(k)) {
           alert(y[k]); // value
           alert(k); // key

No comments: