How to convert JSON to Array in Javascript

12,807

Solution 1

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.

Solution 2

You can simply try on followings:

var arr = Object.keys(obj).map(function(k) { return obj[k] });
Share:
12,807
jane
Author by

jane

Updated on June 06, 2022

Comments

  • jane
    jane almost 2 years

    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 ?

  • jane
    jane over 6 years
    thanks for you answer but I try in filename.js it's return $ is not defined. I wrong ?
  • Shiladitya
    Shiladitya over 6 years
    @jane You forgot to add jQuery library file. Add <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jque‌​ry.min.js"></script> in the head section
  • jane
    jane over 6 years
    I use node.js and I try var jquery = require('jquery'); it's return $ is not defined again.
  • jane
    jane over 6 years