如何将JSON对象键转换为不同的数组

时间:2019-04-18 06:33:55

标签: javascript jquery

有什么想法可以将此JSON对象从对象键转换为不同的数组?

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

期望的数组:

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

我正在尝试类似的操作,但不起作用:

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

2 个答案:

答案 0 :(得分:0)

您可能希望将其存储到对象中,而不是使用单个数组变量。像这样:

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']);

答案 1 :(得分:0)

这是使用jQuery的简单解决方案。希望对您的项目有帮助。

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>