observatoire
observatoire

Reputation: 167

Convert JSON to list of arrays

How can I convert my JSON to a list of arrays

My JSON is Serie :

[{"Value":10,"ValuePourcent":2},{"Value":20,"ValuePourcent":3},{"Value":51,"ValuePourcent":1}]

I would like this format:

[[10,2],[20,3],[:51,1]]

Here's my code so far:

var linq = Enumerable.From(rows);

var Serie = linq
                .GroupBy("$.Year", null,
                    function(key, g) {
                        var result = {
                            Value: g.Sum("$.Car"),
                            ValuePourcent: g.Sum("$.CarPourcent")/Total*100,
                        };
                        return result;
                    })
                .ToArray()

Upvotes: 2

Views: 127

Answers (4)

Jawdat Nassar
Jawdat Nassar

Reputation: 1

var json = [{"Value":10,"ValuePourcent":2},{"Value":20,"ValuePourcent":3},{"Value":51,"ValuePourcent":1}];
var data = $.parse(JSON(json))
var array = [];
var keys = Object.keys(json);
keys.forEach(function(key){
    array.push(json[key]);
    array.push(data[key]
});

Upvotes: 0

Vimal V Nair
Vimal V Nair

Reputation: 16

You can use map

dataArray = [{"Value":10,"ValuePourcent":2},{"Value":20,"ValuePourcent":3},{"Value":51,"ValuePourcent":1}]

newFormat = dataArray.map(function(e){
                  return [e["Value"], e["ValuePourcent"]]
                  });

Upvotes: 0

James Donnelly
James Donnelly

Reputation: 128771

A simple for loop does the trick:

var data = [
  {"Value":10,"ValuePourcent":2},
  {"Value":20,"ValuePourcent":3},
  {"Value":51,"ValuePourcent":1}
];

var result = [];

for (var i = 0; i < data.length; i++) {
  var datum = data[i];
  
  result.push([datum.Value, datum.ValuePourcent]);
}

console.log(result);

Upvotes: 2

aiko
aiko

Reputation: 432

You can try to loop through the json array like this:

var json = JSON.parse("[{\"Value\":10,\"ValuePourcent\":2},{\"Value\":20,\"ValuePourcent\":3},{\"Value\":51,\"ValuePourcent\":1}]");
var newArray = [];

for(var i = 0; i < json.length; i++) {
    newArray.push([
        json[i].Value,
        json[i].ValuePourcent
    ]);
}

Upvotes: 1

Related Questions