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] });
Author by
jane
Updated on June 06, 2022Comments
-
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 over 6 yearsthanks for you answer but I try in filename.js it's return $ is not defined. I wrong ?
-
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/jquery.min.js"></script>
in the head section -
jane over 6 yearsI use node.js and I try var jquery = require('jquery'); it's return $ is not defined again.
-
jane over 6 yearshelp me again , please. stackoverflow.com/questions/45952057/…