Gian
Gian

Reputation: 674

JSON data to JavaScript

When I do JArray.toSource(), I get this:-

[{selectionID:"1", cnt:"5"}, {selectionID:"2", cnt:"2"}, {selectionID:"3", cnt:"1"}]

How can I convert JArray to format like this:-

[[1,5],[2,2],[3,1]]

in JavaScript.

Eventually I want newJArray.toSource() become [[1,5],[2,2],[3,1]]

Upvotes: -1

Views: 120

Answers (2)

peterfoldi
peterfoldi

Reputation: 7471

pimvdb's solution is very nice. My comment is that in this particular case this is enough:

array.map(function(arrayItem) {
    return [arrayItem.selectionID, arrayItem.cnt];
});

It is uglier (more specific), but my gut feeling is that it's much more efficient (and sometimes that matters).

Upvotes: 1

pimvdb
pimvdb

Reputation: 154818

You can use Object.keys which returns the keys, and map to map the array as such:

array.map(function(arrayItem) {
  return Object.keys(arrayItem).map(function(objectKey) {
    return +arrayItem[objectKey]; // convert to number
  });
});

Basically, you replace each element in the array with the values of the object.

Upvotes: 3

Related Questions