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>" );
});
});
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>" );
});
});
Share
edited Sep 28, 2017 at 14:17
Shiladitya
12.2k17 gold badges28 silver badges42 bronze badges
asked Sep 28, 2017 at 14:10
HasenHasen
12.4k29 gold badges85 silver badges140 bronze badges
3
- 1 Can you give a sample of the file you are parsing? – Simon Brahan Commented Sep 28, 2017 at 14:19
-
What is
key
currently giving you? – Andy Commented Sep 28, 2017 at 14:32 - Key gives some number gradually increasing in value like 66, 69, 87 etc and the value is text. That's what is in the json file. – Hasen Commented Sep 29, 2017 at 13:10
4 Answers
Reset to default 3For 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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
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);
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.
$.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>" );
}
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744919069a4601019.html
评论列表(0条)