Reputation: 665
I'm trying to display all of the items in my list below. I organized them as such in order to filter them out.
For example, I want all the titles to be separate from the array items they contain (so that the titles will display as headers and the items as regular text.
Here is my code so far:
var general = {
"Hardcover" : {
["Book A",4],
["Book B",6],
["Book C",5]
}
// ... other options
};
for (var title in general) {
var title = ...; // assign the title variable
$('body').append("<h2>" + title + "</h2>");
for(var items in title) {
// assign item variables separately
var itemTitle = ...;
var itemPrice = ...;
$('body').append(itemTitle + ": $" + itemPrice);
}
}
So the final output would look something like:
Book A: $4
Book B: $6
Book C: $5
I made a quick fiddle below with my full list: http://jsfiddle.net/gekp6q8y/1/
Upvotes: 0
Views: 8899
Reputation: 41
http://jsfiddle.net/gekp6q8y/3/
$( document ).ready(function() {
var general = {
"Hardcover": [
["Book A", 4],
["Book B", 6],
["Book C", 5]
],
"Ebooks": [
["Ebook A", 14],
["Ebook B", 98]
],
"PDFs": [
["PDF A", 2],
["PDF B", 1],
["PDF C", .5]
],
"Free Texts": [
["FA A", 4],
["FA B", 6],
["FA C", 5]
],
};
for (var title in general) {
$(".contSelf").append("<h1 > " + title + "</h1>");
for (var bookArr in general[title]) {
// console.log(general[title][book]);
var book = general[title][bookArr];
$(".contSelf").append("<li class='book' > " + book[0] + ' :$' + book[1] + "</li>");
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='contSelf'></div>
Upvotes: 1
Reputation: 5286
Objects cannot hold multiple arrays like that. Objects are a data structure that hold key/value pairs. By simply adding arrays separated by commas into the hardcover
object, you're treating it like an array (but with curly braces instead of brackets). The Javascript interpreter will reject this.
You can set bookA
, bookB
, bookC
, etc. as keys with their amount as its value. Or you can just give it keys with numbers or something in it:
var general = {
hardcover: {
1: ['Book A', 4],
2: ['Book B', 6],
3: ['Book C', 5]
}
};
Then to iterate:
for (var key in general) {
$('body').append('<h2>' + key + '</h2>');
for (var book in key) {
var itemTitle = book[0];
var itemPrice = book[1];
$('body').append(itemTitle + ': $' + itemPrice)
}
}
Alternately, you can have hardcover
be a key which stores an array of arrays within general
:
var general = {
hardcover: [
['Book A', 4], ['Book B', 6], ['Book C', 5]
]
};
From here, you would iterate slightly differently:
for (var key in general) {
$('body').append('<h2>' + key + '</h2>');
general[key].forEach(function(elem) {
var itemTitle = elem[0];
var itemPrice = elem[1];
$('body').append(itemTitle + ': $' + itemPrice)
})
}
Upvotes: 3