Reputation: 1670
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
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
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
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();
Upvotes: 0
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.
Upvotes: 3
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)
});
}
}
Upvotes: 1