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
asked Mar 3, 2017 at 10:03
Giant
1,6497 gold badges34 silver badges70 bronze badges
2 Answers 2
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>
answered Mar 3, 2017 at 10:07
Brent Boden
5792 silver badges10 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Giant
i need 9 mins to tick
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);
});
answered Mar 3, 2017 at 10:17
Yogesh Mistry
2,17018 silver badges20 bronze badges
Comments
lang-js
each()method docs before posting here? In your question I already see you addi, vinside the function, which meansindexandvalue.iis the index you are looking for.