whyAto8
whyAto8

Reputation: 1670

jquery each not working propertly while looping through

I am not able to figure out, why this code (only js) is not running - http://jsfiddle.net/fLEAw/

populateList();
populateList: function () {
        var accData = [{ A: "A1" }, { B: "B1"}];

    $.each(accData, function (index) {
            alert(accData[index].Value)
        });

    }

Upvotes: 2

Views: 127

Answers (5)

rajesh kakawat
rajesh kakawat

Reputation: 10896

try something like this

var accData = [{ A: "A1" }, { B: "B1"}];
$.each(accData, function (index,obj) {
  $.each(obj, function(key, value) {
    alert(key + '' + value);
  });
});

Upvotes: 0

elclanrs
elclanrs

Reputation: 94101

You can use $.each to loop arrays and objects:

$.each(accData, function(i, obj) {    
  $.each(obj, function(k, value) {
    alert(value);
  });
});

I doubt you'll end up using alert, you probably want the values to do something with them, so you can put them in an array. Here's an alternative re-usable approach in plain JavaScript:

var values = function(obj) {
  var result = [];
  for (var i in obj) {
    result.push(obj[i]);
  }
  return result;
};

var flatten = function(xs) {
  return Array.prototype.concat.apply([], xs);
};

var result = flatten(accData.map(values));

console.log(result); //=> ["A1", "B1"]

Upvotes: 2

Dhanu Gurung
Dhanu Gurung

Reputation: 8840

Since your array element is object, try this solution:

var populateList = function () {
  var accData = [{ A: "A1" }, { B: "B1"}];

  $.each(accData, function (index) {    
    for(var ele in accData[index]){
      alert(accData[index][ele]);
    }
  });

};
populateList();

Demo

Upvotes: 0

zzlalani
zzlalani

Reputation: 24364

You javascript/jquery code has multiple issues. have a look at this

var populateList = function () {
    var accData = [{ A: "A1" }, { B: "B1"}];

    $.each(accData, function (index) {
        for(var value in accData[index]){
            alert(accData[index][value])
        }

    });

}

populateList();

I would rather suggest you to rectify the issues your self and ask in comment.

http://jsfiddle.net/fLEAw/3/

Upvotes: 3

codingrose
codingrose

Reputation: 15699

Change

populateList: function () {

to

function populateList() {

Write:

populateList();
function populateList() {
    var accData = [{
        A: "A1"
    }, {
        B: "B1"
    }];
    var len = accData.length;
    for (var i = 0; i < len; i++) {
        $.each(accData[i], function (key, value){
            //key will return key like A,B and value will return values assigned
            alert(value)
        });
    }
}

Updated fiddle here.

Upvotes: 1

Related Questions