Hasen
Hasen

Reputation: 12343

jQuery .each get index of items

The array fetched has a key and value for each item but I want to get a simple index for each value ie 0, 1, 2, 3, 4 etc which currently is not what the key gives (and nor do I want it to). Using index also does not seem to work.

$.getJSON( "filepath/current.json", function(data) {
  var items = [];
  $.each( data, function(key,val) {
    items.push( "<p id='" + key + "'>" + val + "</p>" );
  });
});

Upvotes: 1

Views: 10815

Answers (4)

mscdeveloper
mscdeveloper

Reputation: 2889

$.getJSON( "filepath/current.json", function(data) {
  var items = [];
  for(key in data) {
      var insert_key=parseInt(key)||0;
      items.push( "<p id='" + insert_key + "'>" + data[key] + "</p>" );
  }        
});

Upvotes: 0

Thusitha
Thusitha

Reputation: 3511

For objects jQuery each doesn't support for an index parameter. But you can create an index for your own without any problems. ;)

var data = {
    one: "ONE",
    two: "TWO",
    three: "THREE"
  },
  items = [];

//Use a simple counter ;)

(function() {
  var i = 0;
  $.each(data, function(key, val) {
    items.push("<p id='" + i + "'>" + val + "</p>");
    i++;
  });
})();

console.log(items);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 3

sztrzask
sztrzask

Reputation: 119

The key property is literally the index. If the key isn't a numeric index then your data is not an array but an object.

Your choices are:

a) rethink and redesign the solution. What are you going to use 0, 1, 2 etc for? Can it be replaced?

b) introduce a variable outside the each scope and manually increment it inside the scope. If you need to access the val later using the numeral index, you should map that data object to an array of objects containing only key and val properties.

Upvotes: 0

Faly
Faly

Reputation: 13356

Try this:

var data = ["aa", "bb", "cc"];
var items = data.map((val, index) => "<p id='" + index + "'>" + val + "</p>");
console.log(items);

And it even cleaner with ECMAScrpt6 template litteral:

var data = ["aa", "bb", "cc"];
var items = data.map((val, index) => `<p id='${index}'>${val}</p>`);
console.log(items);

Upvotes: 0

Related Questions