I am having trouble having the keys (“Apple iPhone 5S“, “Solio Mono Solar Charger“, “24 Month Warranty Package“) display in the console. (Basically, display each item with the price.)
I tried using JSON.parse(cart) and used:
var arr = Object.keys(cart.Item).map(function(k) { return cart.Item[k] });
but the console only displays this:
[[object Object] {
price: 299.99,
productId: 688,
url: "http://website.com/phone_iphone5s.html"
}, [object Object] {
price: 29.95,
productId: 655,
url: "http://website.com/solio_charger.html"
}, [object Object] {
price: 129.95,
productId: 681,
url: "http://website.com/24_month_warranty.html"
}]
I did notice that "Item" is written as an object instead of an array. Should I be changing the object into an array so that the ".map" function works?
Here's my JSBin: JSBin
and my Code:
var arr = Object.keys(cart.Item).map(function(k) { return cart.Item[k] });
// var arrStr = JSON.parse(cart);
// console.log(arrStr);
console.log(arr);
function myCart(){
var myLen = cart.Item.count;
console.log("Items: " + cart.Items);
for(var i=0; i<myLen; i++){
console.log("- " + cart.Item[i] + " (" + cart.Item[i].price + ")");
}
console.log("Total: " + cart.Total);
};
myCart();
Here's the original question:
Given the following JSON object as an example:
cart = {
"Items": 3,
"Item": {
"Apple iPhone 5S": {
"productId": 688,
"url": "http://website.com/phone_iphone5s.html",
"price": 299.99
},
"Solio Mono Solar Charger": {
"productId": 655,
"url": "http://website.com/solio_charger.html",
"price": 29.95
},
"24 Month Warranty Package": {
"productId": 681,
"url": "http://website.com/24_month_warranty.html",
"price": 129.95
}
},
"Total": 459.89
}
Write a JavaScript function that outputs the total number of items, each item with price, and the total value of the shopping cart in the browser console in the exact format as shown below. The least amount of code, the better.
Note: The JSON object is just an example. The code should work for ANY JSON object with the same structure so do not use hardcoded keys (“Apple iPhone 5S“, “Solio Mono Solar Charger“, “24 Month Warranty Package“).
RESULT:
Items: 3
- Apple iPhone 5S ($299.99)
- Solio Mono Solar Charger ($29.95)
- 24 Month Warranty Package ($129.95)
Total: 459.89