Answer for Q1:
Basically all you have to do is to use the (for .. in .. ) loop to use all properties of an object. (the types object in this case)
var JsonVar;
$.getJSON("https://api.myjson.com/bins/1ba5at", function(jsonData) {
var types = {};
jsonData.forEach(function(item) {
if (!types[item.keyword]) {
types[item.keyword] = 0;
}
types[item.keyword]++;
});
for (var typeKey in types) {
var newLiElement = document.createElement("li");
var valueSpanElement = document.createElement("span");
var valueTextNode = document.createTextNode(typeKey.toString());
var keyTextNode = document.createTextNode("keyword: ");
var countSpanElement = document.createElement("span");
var countSpanText = document.createTextNode(types[typeKey].toString());
//here you can style the keys
valueSpanElement.setAttribute("style", "background-color: blue; color: white;");
countSpanElement.setAttribute("style", "margin-left: 10px; background-color: black; color: white; text-weight: bold;");
countSpanElement.appendChild(countSpanText);
valueSpanElement.appendChild(valueTextNode);
newLiElement.appendChild(keyTextNode);
newLiElement.appendChild(valueSpanElement);
newLiElement.appendChild(countSpanElement);
document.getElementById("menu").appendChild(newLiElement);
}
});
Here is the fiddle link: https://jsfiddle.net/k8xn0n5v/5/
Answer for Q2:
All you have to do is to create an array from the string keywords using the string.split() method. (in this case, the ', ' argument will work fine)
I have updated the fiddle, now you can find the keyword:count values in an array.
https://jsfiddle.net/5089L59x/15/
Extending the code of your fiddle looks like this:
var JsonVar;
$.getJSON("https://api.myjson.com/bins/lz839", function(jsonData) {
var types = {};
jsonData.forEach(function(item) {
if (!types[item.keyword]) {
types[item.keyword] = 0;
}
types[item.keyword]++;
});
var keywordsCountObject = {};
for (var typeKey in types) {
var keywordItemsToCount = typeKey.toString().split(", ");
keywordItemsToCount.forEach(function(itemToCount) {
console.log(itemToCount);
if (!keywordsCountObject.hasOwnProperty(itemToCount)) {
keywordsCountObject[itemToCount] = 1;
} else {
keywordsCountObject[itemToCount]++;
}
});
}
for (var prop in keywordsCountObject) {
$("ul#menu").append("<li>" + prop + " " + keywordsCountObject[prop].toString() + "</li>");
}
});