且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Javascript中将JSON转换为数组

更新时间:2023-01-09 22:10:30

您的预期输出的语法不正确,因为您不能有没有键值对的对象.

The syntax of your expected output is incorrect as you cant have object without key value pair.

您可以将输出设置为

{
  "data" : [ [ 1, "Alex", 20 ]  ]
},
{
  "data" : [[ 2, "Zara", 18 ]  ,
           [ 2, "Zara", 19 ]  ]
}

这是考虑上述输出的解决方案

var inputArr = [
  {
    "data" : [
          {
            "month" : 1,
             "name" : "Alex",
             "sum" : 20
          }
      ]  
  },
  {
    "data" : [
          {
            "month" : 2,
             "name" : "Zara",
             "sum" : 18
          },
          {
            "month" : 2,
            "name" : "Zara",
            "sum" : 19
          }
      ]  
  }
];

inputArr.forEach(function(item){
    for (var i=0; i< item.data.length; i++){
        var myArr = [];
        myArr.push(item.data[i].month);
        myArr.push(item.data[i].name);
        myArr.push(item.data[i].sum);
        item.data[i] = myArr;
    }
})

console.log(JSON.stringify(inputArr));

注意:如果可以在代码中使用ES6,则可以简化解决方案.

NOTE: Solution can be simplified if you are Ok to use ES6 in your code.