0

any ideas to convert this JSON object to different arrays from the object keys?

json= [
    {  "Count": 6,  "plant": 18,  "Stressed": 4  },
    {  "Count": 9,  "plant": 19,  "Stressed": 5 },
    {  "Count": 4,  "plant": 15,  "Stressed": 3 }
]

Expected arrays:

count=[6,9,4];  
plant=[18,19,15];  
Stressed=[4,5,3] ;

I'm trying something like this but does not work:

$.each(json, function (k, v) {
    var arr = Array.from(Object.keys(v),k=>v[k]);
    console.log(arr);
})
200313
  • 327
  • 3
  • 5

2 Answers2

1

You might want to store it into object rather than having individual array variable. Like this:

json = [{
    "Count": 6,
    "plant": 18,
    "Stressed": 4
  },
  {
    "Count": 9,
    "plant": 19,
    "Stressed": 5
  },
  {
    "Count": 4,
    "plant": 15,
    "Stressed": 3
  }
];
var new_data = {};

for (var data of json) {
  for (var key in data) {

    if (typeof new_data[key] == 'undefined') {
      new_data[key] = [];
    }
    new_data[key].push(data[key]);
  }
}
console.log('Count:');
console.log(new_data['Count']);
console.log('plant:');
console.log(new_data['plant']);
console.log('Stressed:');
console.log(new_data['Stressed']);
ACD
  • 1,431
  • 1
  • 8
  • 24
0

this is a simple solution using jQuery. Hope, it will help in your project.

var json= [
    {
        "Count": 6, 
        "plant": 18,  
        "Stressed": 4  
    },
    {  
        "Count": 9,
        "plant": 19,
        "Stressed": 5 
    },
    {  
        "Count": 4,
        "plant": 15,
        "Stressed": 3 
    }
];

var count = [];
var plant = [];
var stressed = [];

$.each(json, function (k, v) {
    count.push(v.Count);
    plant.push(v.plant);
    stressed.push(v.Stressed);
});

console.log(count);
console.log(plant);
console.log(stressed);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Sami Ahmed Siddiqui
  • 2,328
  • 1
  • 16
  • 29
Jakir Hossen
  • 451
  • 4
  • 13
  • I actually used that at first. The problem appeared when you have more than three arrays and want them to be automatically created. '$.each' would require more code than 'for'... At least I didn't find an efficient way using $.each yet, but I would like to. – 200313 Apr 22 '19 at 06:07