简体   繁体   中英

Extract values from json in javascript

How could I itterate through the json and extract the values for each task (ie "AMS Upgrade" and "BMS works" are the tasks) from the following json string, I have tried using the code below, but no success.

note that AMS Upgrade and BMS works are variables so the code should not reference them

during each loop, i want to be able to console log the following

1st loop

Task Description: AMS Upgrade

Total: 30667.303111791967

% Complete to end: 1.0

value claimed: 25799.788761888347

2nd loop

Task Description: BMS works

Total: 35722.8761704046

% Complete to end: 0.1

value claimed: 3572.2876170404597

 var data = `{"line_items": {"AMS Upgrade": [{"Total": 30667.303111791967}, {"% Complete to end": 1.0}, {"value claimed": 25799.788761888347}], "BMS works": [{"Total": 35722.8761704046}, {"% Complete to end": 0.1}, {"value claimed": 3572.2876170404597}]}}` var obj = JSON.parse(data); console.log("processing data..."); console.log(obj); console.log(obj.line_items[1].Total); 

 const obj = { "line_items": { "AMS Upgrade": [{ "Total": 30667.303111791967 }, { "% Complete to end": 1.0 }, { "value claimed": 25799.788761888347 }], "BMS works": [{ "Total": 35722.8761704046 }, { "% Complete to end": 0.1 }, { "value claimed": 3572.2876170404597 }] } }; const totals = Object.keys(obj.line_items).map(valInner => obj.line_items[valInner][0].Total); console.log(totals); /* Updated code for inner values */ Object.keys(obj.line_items).forEach(valInner => { obj.line_items[valInner].forEach((val) => { for (const i in val) { console.log(`${i} = ${val[i]}`); } }); }); 

Here is way using for..in .

 const data = {"line_items": {"AMS Upgrade": [ {"Total": 30667.303111791967}, {"%Complete to end": 1.0}, {"value claimed": 25799.788761888347}], "BMSworks": [ {"Total": 35722.8761704046}, {"%Complete to end": 0.1}, {"value claimed": 3572.2876170404597}] } } let totals = []; for(let key in data.line_items){ totals.push(data.line_items[key][0].Total); } console.log(totals) //Combining all other like Total for(let key in data.line_items){ console.log("Task Description:" + key); data.line_items[key].forEach(value => { let k = console.log(`${Object.keys(value)}:${Object.values(value)[0]}`) }) } 

You can take the values and get the total out of from value. Since in your structure you have total only at 0th index you can directly access 0th index if order is not fixed than you can use find.

 let obj = {"line_items": {"AMS Upgrade": [{"Total": 30667.303111791967}, {"% Complete to end": 1.0}, {"value claimed": 25799.788761888347}], "BMS works": [{"Total": 35722.8761704046}, {"% Complete to end": 0.1}, {"value claimed": 3572.2876170404597}]}} let Total = Object.values(obj.line_items).map(e=>e[0].Total) console.log(Total) 

how can i loop through the json and get on each run all thses values together, the name, Total, %_complete_to_end: and value_claimed

 let obj = {"line_items": {"AMS Upgrade": [{"Total": 30667.303111791967}, {"% Complete to end": 1.0}, {"value claimed": 25799.788761888347}], "BMS works": [{"Total": 35722.8761704046}, {"% Complete to end": 0.1}, {"value claimed": 3572.2876170404597}]}} let Total = Object.values(obj.line_items).map(e=> e.map(el=> Object.values(el))) console.log(Total) 

As you want the those items as variable. Look for theKeyWeWantToget variable.

  var data = `{"line_items": {"AMS Upgrade": [{"Total": 30667.303111791967}, {"% Complete to end": 1.0}, {"value claimed": 25799.788761888347}], "BMS works": [{"Total": 35722.8761704046}, {"% Complete to end": 0.1}, {"value claimed": 3572.2876170404597}]}}` var obj = JSON.parse(data); console.log("processing data..."); console.log(obj); var theKeyWeWantToget = "AMS Upgrade"; console.log(obj.line_items[theKeyWeWantToget][0].Total); theKeyWeWantToget = "BMS works"; console.log(obj.line_items[theKeyWeWantToget][0].Total); 

This is your JSON string/object

{
    "line_items": {
        "AMS Upgrade": [{
            "Total": 30667.303111791967
        }, {
            "% Complete to end": 1.0
        }, {
            "value claimed": 25799.788761888347
        }],
        "BMS works": [{
            "Total": 35722.8761704046
        }, {
            "% Complete to end": 0.1
        }, {
            "value claimed": 3572.2876170404597
        }]
    }
}

Accessing Total should be

var totals=[]; //array to store totals.
for(var key in obj.line_items)
{
   totals.push(obj.line_items[key][0].Total);
}

try it like this

var obj = JSON.parse(data);                 
console.log("processing data...");
console.log(obj); 
console.log(obj.line_items["AMS Upgrade"][0]);

The line_itmes has "AMS Upgrade" filed and then the "AMS Upgrade" has array . So you have to access through array.

ES6 Variant: Works no matter at what index your total lies.

 // ES6 variant. const test = { "line_items": { "AMS Upgrade": [{ "Total": 30667.303111791967 }, { "% Complete to end": 1.0 }, { "value claimed": 25799.788761888347 }], "BMS works": [{ "Total": 35722.8761704046 }, { "% Complete to end": 0.1 }, { "value claimed": 3572.2876170404597 }] } }; console.log(test["line_items"]["AMS Upgrade"].map(key => key['Total']).filter(val => !!val)[0]); console.log(test["line_items"]["BMS works"].map(key => key['Total']).filter(val => !!val)[0]); 

With your original structure, the following will work:

Object.keys(obj.line_items).forEach(key => console.log(obj.line_items[key][0].Total))

The structure you have for the JSON could be improved to make working with it easier. I would recommend something more along the lines of the following if you have control over the source data:

const data = { line_items: [
    { 
       name: "AMS Upgrade"
       total: 30667.303111791967,
       %_complete_to_end: 1.0,
       value_claimed: 25799.788761888347
    },
    {
        name: "BMSworks",
        total: 35722.8761704046,
        %_complete_to_end: 0.1,
        value_claimed: 3572.2876170404597
    }
]}

In the first part I'm just parsing JSON data, after I store each array in a variable (this is not necessary) and in the third part I make a console.log of each element of the array

 /** *Part 1 */ var data = JSON.parse(`{"line_items": {"AMS Upgrade": [{"Total": 30667.303111791967}, {"% Complete to end": 1.0}, {"value claimed": 25799.788761888347}], "BMS works": [{"Total": 35722.8761704046}, {"% Complete to end": 0.1}, {"value claimed": 3572.2876170404597}]}}`); /** *Part 2 */ var amsUpgrade = data['line_items']['AMS Upgrade']; console.log('AMS Upgrade : ', amsUpgrade); /** *Part 3 */ console.log('AMS Upgrade Total : ', amsUpgrade[0]['Total']); console.log('AMS Upgrade % Complete to end : ', amsUpgrade[1]['% Complete to end']); console.log('AMS Upgrade value claimed', amsUpgrade[2]['value claimed']); var bmsWorks = data['line_items']['BMS works']; console.log('BMS works : ', bmsWorks); console.log('BMS works Total : ', bmsWorks[0]['Total']); console.log('BMS works % Complete to end : ', bmsWorks[1]['% Complete to end']); console.log('BMS works value claimed', bmsWorks[2]['value 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