-4

I have a json response like this,

"meteo_inverter_analysis":{  
    "Id93922.1":{  
        "inverter_id":"Id93922.1", "total_electricity_generated":1567.7910000000002
    },
    "Id93922.2":{  
        "inverter_id":"Id93922.2", "total_electricity_generated":1468.4869999999999
    },
    "Id93922.3":{  
        "inverter_id":"Id93922.3","total_electricity_generated":498.7319999999999
    },
    "Id93922.4":{  
        "inverter_id":"Id93922.4","total_electricity_generated":461.8369999999999
    }

}

from that response i want to create an js array from total_electricity_generated. The array would be: var array = [1567.7910000000002, 1468.4869999999999, 498.7319999999999, 461.8369999999999]

Can anyone help me how to do it? TIA

Alauddin Ahmed
  • 1,128
  • 2
  • 14
  • 34
  • 1
    Iterate over the JSON data ,and store that value in the array [Refer this if you don't know how to do it](https://stackoverflow.com/questions/19323699/iterating-through-json-object-javascript) – dheeraj tripathi Mar 17 '18 at 16:21
  • Related: [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Jonathan Lonowski Mar 17 '18 at 16:28

2 Answers2

1

You can get the keys of the meteo_inverter_analysis and then loop over to that keys to get the property value of Id93922.*

var data = {"meteo_inverter_analysis":{  
    "Id93922.1":{  
        "inverter_id":"Id93922.1",     
         "total_electricity_generated":1567.7910000000002
    },
    "Id93922.2":{  
        "inverter_id":"Id93922.2",
        "total_electricity_generated":1468.4869999999999
    },
    "Id93922.3":{  
        "inverter_id":"Id93922.3",
        "total_electricity_generated":498.7319999999999
    },
    "Id93922.4":{  
        "inverter_id":"Id93922.4",
        "total_electricity_generated":461.8369999999999
    }
}
};

var keys = Object.keys(data.meteo_inverter_analysis);
var arr = keys.map(key => data.meteo_inverter_analysis[key].total_electricity_generated
);

console.log(arr);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
1

I think the following example will help you:

 <script>
  var car =new Array();
  var myObj, i;
  myObj = {
 "name":"John",
 "age":30,
 "cars":[ "Ford", "BMW", "Fiat" ]
 };

 for (i = 0; i < myObj.cars.length; i++) {
 car[i]= myObj.cars[i] + "<br>";
 }

</script>
quantik
  • 776
  • 12
  • 26