使用JavaScript从JSON提取键值

时间:2019-02-12 09:55:17

标签: javascript extract

如何控制台 AMS升级 BMS正常运行,请注意,这些是变量,因此解决方案不应直接引用上述字符串值。我成功地按照下面的代码获取了所有值,除了它们。

代码:

const data = {"line_items": 
    {"AMS Upgrade": [
        {"Total": 30667.303111791967},
        {"complete": 1.0},
        {"claimed": 25799.788761888347}],
    "BMS works":    [
        {"Total": 35722.8761704046},
        {"complete": 0.1},
        {"claimed": 3572.2876170404597}]
    }
}
let totals = [];
for(let key in data.line_items){
  console.log(data['line_items'][1])
  console.log(data.line_items[key][0].Total)
  console.log(data.line_items[key][1].complete)
  console.log(data.line_items[key][2].claimed)

} 

2 个答案:

答案 0 :(得分:1)

您已经有将其放入变量的代码:

for (let key in data.line_items) {

只需记录key的值。

const data = {
  "line_items": {
    "AMS Upgrade": [{
        "Total": 30667.303111791967
      },
      {
        "complete": 1.0
      },
      {
        "claimed": 25799.788761888347
      }
    ],
    "BMS works": [{
        "Total": 35722.8761704046
      },
      {
        "complete": 0.1
      },
      {
        "claimed": 3572.2876170404597
      }
    ]
  }
}
let totals = [];
for (let key in data.line_items) {
  console.log(key);
}

答案 1 :(得分:0)

const data = {"line_items": 
    {"AMS Upgrade": [
        {"Total": 30667.303111791967},
        {"complete": 1.0},
        {"claimed": 25799.788761888347}],
    "BMS works":    [
        {"Total": 35722.8761704046},
        {"complete": 0.1},
        {"claimed": 3572.2876170404597}]
    }
}
let totals = [];
for(let key in data.line_items){
  console.log(key)
  console.log(data.line_items[key][0].Total)
  console.log(data.line_items[key][1].complete)
  console.log(data.line_items[key][2].claimed)

}