0
 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
 }

我想编写一个JavaScript函数,在浏览器开发工具控制台中输出商品总数、每个商品的价格以及购物车的总值。例如:需要选择Apple Iphone 5S 及其价格、Solio Mono Solar Charger 及其价格等。不使用硬编码键(例如“Apple iPhone 5S”、“Solio Mono Solar Charger”)。有什么办法吗??

有可能获得这种格式吗?

   Items: 3 
    - Apple iPhone 5S ($299.99) 
    - Solio Mono Solar Charger ($29.95) 
    - 24 Month Warranty Package ($129.95)
   Total: 459.89 
4

2 回答 2

0

你在找这样的东西吗

var str = `Items: ${cart.Items} `;
Object.keys(cart.Item).forEach((key) => {
  str += `- ${key} (${cart.Item[key].price}) `
})

str +=  `Total: ${cart.Total}`
console.log(str)

var 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
}


var str = `Items: ${cart.Items} `;
Object.keys(cart.Item).forEach((key) => {
  str += `- ${key} (${cart.Item[key].price}) `
})

str +=  `Total: ${cart.Total}`
console.log(str)

于 2018-01-18T12:24:40.953 回答
0

您可以遍历它们并像这样获取想要的数据。

您可以对其进行编辑以适合您需要的任何内容。

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
 }

for (var key in cart.Item) {
    if (cart.Item.hasOwnProperty(key)) {
        console.log(key + " " + cart.Item[key]);
    }
}
于 2018-01-18T12:35:40.840 回答