简体   繁体   中英

Extract key value from json using javascript

How can I console log AMS Upgrade and BMS works , note that these are variables, so the solution should not directly reference the above string value. i am successful in getting all values as per code below except for them.

Code:

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)

} 

You already have code that puts them in a variables:

 for (let key in data.line_items) {

Just log the value of 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); }

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)

} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM