使用Javascript在不使用硬编码键的情况下提取JSON对象值/键

时间:2018-01-18 12:19:48

标签: javascript jquery json object jsonparser

 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太阳能充电器及其价格等。不使用 硬编码密钥 (例如“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 

2 个答案:

答案 0 :(得分: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)




答案 1 :(得分: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]);
    }
}