Reputation: 1649
var data = [{
"amount": "1",
"year": "2017",
"month": "March"
}, {
"amount": "1",
"year": "2017",
"month": "April"
}, {
"amount": "1",
"year": "2017",
"month": "May"
}];
$.each(JSON.parse(data), function(i, v) {
console.log(v.index())
console.log(v.amount)
console.log(v.year)
console.log(v.month)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
How to get the index of an object that is inside an array using .each()
Currently I am using .index()
but it is not working for me
Upvotes: 0
Views: 70
Reputation: 2152
Firstly, you don't need to use JSON.parse()
.
Secondly, you are already passing index and value as parameters to the anonymous closure function inside .each()
Snippet for your reference:
$.each(data, function(i,v){
console.log("index of object in array: "+i);
});
Upvotes: 0
Reputation: 579
var data = [{
"amount": "1",
"year": "2017",
"month": "March"
}, {
"amount": "1",
"year": "2017",
"month": "April"
}, {
"amount": "1",
"year": "2017",
"month": "May"
}];
$.each(data, function(i, v) {
//i is the index and v is the value
console.log(i);
console.log(v.amount);
console.log(v.year);
console.log(v.month);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1