0

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

5
  • 1
    just use your "i" variable to get the current index Commented Mar 3, 2017 at 10:06
  • index is the first parameter from the function ex:- i Commented Mar 3, 2017 at 10:08
  • 1
    Have you looked over the each() method docs before posting here? In your question I already see you add i, v inside the function, which means index and value. Commented Mar 3, 2017 at 10:12
  • You don't need to parse your object here. And, i is the index you are looking for. Commented Mar 3, 2017 at 10:13
  • @Ionut that is what i missed still learning Commented Mar 3, 2017 at 10:16

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

i need 9 mins to tick
0

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.