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 ?
You can simply try on followings:
var arr = Object.keys(obj).map(function(k) { return obj[k] });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With