Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JSON to Array in Javascript

I want to convert JSON to Array and I return value by : console.log(data);

value is :

[{ "data" : [  [object]  ] },
[{ "data" : [  [object] , [object]  ] }

so, I converted to JSON by:

console.log(JSON.stringify(data, null, "    "));

value is :

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

]

I want convert to Array :

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

How to convert ?

like image 513
jane Avatar asked Jul 17 '26 01:07

jane


2 Answers

You can simply try on followings:

var arr = Object.keys(obj).map(function(k) { return obj[k] });
like image 54
Kunvar Singh Avatar answered Jul 18 '26 15:07

Kunvar Singh


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

you can have your output as

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

here is the solution considering above output

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

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

like image 26
Nemani Avatar answered Jul 18 '26 14:07

Nemani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!